<!DOCTYPE html>
<!-- saved from url=(0031)https://evileg.com/ru/post/494/ -->
<html lang="ru" itemscope="" itemtype="http://schema.org/Article"><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1"><link rel="apple-touch-icon-precomposed" sizes="57x57" href="https://evileg.com/static/images/favicons/apple-touch-icon-57x57.png"><link rel="apple-touch-icon-precomposed" sizes="72x72" href="https://evileg.com/static/images/favicons/apple-touch-icon-72x72.png"><link rel="apple-touch-icon-precomposed" sizes="114x114" href="https://evileg.com/static/images/favicons/apple-touch-icon-114x114.png"><link rel="apple-touch-icon-precomposed" sizes="120x120" href="https://evileg.com/static/images/favicons/apple-touch-icon-120x120.png"><link rel="apple-touch-icon-precomposed" sizes="144x144" href="https://evileg.com/static/images/favicons/apple-touch-icon-144x144.png"><link rel="apple-touch-icon-precomposed" sizes="152x152" href="https://evileg.com/static/images/favicons/apple-touch-icon-152x152.png"><link title="EVILEG - Социальная сеть порграммистов" rel="alternate" type="application/rss+xml" href="https://evileg.com/ru/feed/"><link title="EVILEG - Форум" rel="alternate" type="application/rss+xml" href="https://evileg.com/ru/forum/feed/"><title>Алгоритм DFS («Depth-first search» или «Поиск в глубину»)</title><meta property="og:title" content="Алгоритм DFS («Depth-first search» или «Поиск в глубину»)"><meta property="og:type" content="website"><meta property="og:url" content="https://evileg.com/ru/post/494/"><meta property="og:image" content="https://evileg.com/static/images/favicons/favicon.ico"><meta property="og:site_name" content="EVILEG"><meta name="google-site-verification" content="vVTpO8SvQTo0QU2hU-zDTBHgHzqr2CGx7ACdQHPlLes"><meta name="yandex-verification" content="c58ddaad8c500539"><meta name="wot-verification" content="5e851b19f7a76433f3dc"><meta name="description" content="Алгоритм DFS («Depth-first search» или «Поиск в глубину»). 
 
  
   Обход
  
  означает посещение всех узлов графа.
  
   «Обход в глубину» или «Поиск в глубину»
  
  - это рекурсивный алгоритм поиска всех вершин графа или древовидной структуры данных. В этой"><link rel="stylesheet" href="./Алгоритм DFS («Depth-first search» или «Поиск в глубину»)_files/css"><link rel="stylesheet" href="./Алгоритм DFS («Depth-first search» или «Поиск в глубину»)_files/materialdesignicons.min.css" media="all" type="text/css"><link rel="stylesheet" href="./Алгоритм DFS («Depth-first search» или «Поиск в глубину»)_files/cropper.min.css"><link rel="stylesheet" href="./Алгоритм DFS («Depth-first search» или «Поиск в глубину»)_files/animate.min.css"><link rel="stylesheet" href="./Алгоритм DFS («Depth-first search» или «Поиск в глубину»)_files/evileg_core.min.css"><script src="./Алгоритм DFS («Depth-first search» или «Поиск в глубину»)_files/f.txt"></script><script type="text/javascript" async="" src="./Алгоритм DFS («Depth-first search» или «Поиск в глубину»)_files/watch.js"></script><script src="./Алгоритм DFS («Depth-first search» или «Поиск в глубину»)_files/f(1).txt" id="google_shimpl"></script><script type="text/javascript" src="./Алгоритм DFS («Depth-first search» или «Поиск в глубину»)_files/context.js" async=""></script><script src="./Алгоритм DFS («Depth-first search» или «Поиск в глубину»)_files/jquery-3.3.1.min.js"></script><script src="./Алгоритм DFS («Depth-first search» или «Поиск в глубину»)_files/js.cookie.min.js"></script><script src="./Алгоритм DFS («Depth-first search» или «Поиск в глубину»)_files/popper.min.js"></script><script src="./Алгоритм DFS («Depth-first search» или «Поиск в глубину»)_files/evileg_core.min.js"></script><script defer="" src="./Алгоритм DFS («Depth-first search» или «Поиск в глубину»)_files/cropper.min.js"></script><script defer="" src="./Алгоритм DFS («Depth-first search» или «Поиск в глубину»)_files/evileg.min.js"></script><script defer="" src="./Алгоритм DFS («Depth-first search» или «Поиск в глубину»)_files/global.min.js"></script><script defer="" src="./Алгоритм DFS («Depth-first search» или «Поиск в глубину»)_files/markdown.min.js"></script><script defer="" src="./Алгоритм DFS («Depth-first search» или «Поиск в глубину»)_files/bootstrap-notify.min.js"></script><script type="application/ld+json">{"@context": "http://schema.org", "@type": "ItemList", "itemListElement": [{"@type": "SiteNavigationElement", "position": 1, "name": "EVILEG", "url": "/ru/"}, {"@type": "SiteNavigationElement", "position": 2, "name": "Статьи", "url": "/ru/knowledge/"}, {"@type": "SiteNavigationElement", "position": 3, "name": "Форум", "url": "/ru/forum/"}, {"@type": "SiteNavigationElement", "position": 4, "name": "Тесты", "url": "/ru/tests/"}, {"@type": "SiteNavigationElement", "position": 5, "name": "Вакансии", "url": "/ru/vacancy/"}, {"@type": "SiteNavigationElement", "position": 6, "name": "Закладки", "url": "/ru/social_bookmarks/"}, {"@type": "SiteNavigationElement", "position": 7, "name": "Идеи", "url": "/ru/ideas/"}, {"@type": "SiteNavigationElement", "position": 8, "name": "Расшарить код", "url": "/ru/sharecode/"}, {"@type": "SiteNavigationElement", "position": 9, "name": "Компании", "url": "/ru/companies/"}, {"@type": "SiteNavigationElement", "position": 10, "name": "Пользователи", "url": "/ru/users/"}, {"@type": "SiteNavigationElement", "position": 11, "name": "Расшарить код", "url": "/ru/sharecode/create/"}, {"@type": "SiteNavigationElement", "position": 12, "name": "Написать статью", "url": "/ru/knowledge/article/add/"}, {"@type": "SiteNavigationElement", "position": 13, "name": "Задать вопрос", "url": "/ru/forum/create_topic/"}]}</script><meta http-equiv="origin-trial" content="AxujKG9INjsZ8/gUq8+dTruNvk7RjZQ1oFhhgQbcTJKDnZfbzSTE81wvC2Hzaf3TW4avA76LTZEMdiedF1vIbA4AAABueyJvcmlnaW4iOiJodHRwczovL2ltYXNkay5nb29nbGVhcGlzLmNvbTo0NDMiLCJmZWF0dXJlIjoiVHJ1c3RUb2tlbnMiLCJleHBpcnkiOjE2NTI3NzQ0MDAsImlzVGhpcmRQYXJ0eSI6dHJ1ZX0="><meta http-equiv="origin-trial" content="Azuce85ORtSnWe1MZDTv68qpaW3iHyfL9YbLRy0cwcCZwVnePnOmkUJlG8HGikmOwhZU22dElCcfrfX2HhrBPAkAAAB7eyJvcmlnaW4iOiJodHRwczovL2RvdWJsZWNsaWNrLm5ldDo0NDMiLCJmZWF0dXJlIjoiVHJ1c3RUb2tlbnMiLCJleHBpcnkiOjE2NTI3NzQ0MDAsImlzU3ViZG9tYWluIjp0cnVlLCJpc1RoaXJkUGFydHkiOnRydWV9"><meta http-equiv="origin-trial" content="A16nvcdeoOAqrJcmjLRpl1I6f3McDD8EfofAYTt/P/H4/AWwB99nxiPp6kA0fXoiZav908Z8etuL16laFPUdfQsAAACBeyJvcmlnaW4iOiJodHRwczovL2dvb2dsZXRhZ3NlcnZpY2VzLmNvbTo0NDMiLCJmZWF0dXJlIjoiVHJ1c3RUb2tlbnMiLCJleHBpcnkiOjE2NTI3NzQ0MDAsImlzU3ViZG9tYWluIjp0cnVlLCJpc1RoaXJkUGFydHkiOnRydWV9"><meta http-equiv="origin-trial" content="AxBHdr0J44vFBQtZUqX9sjiqf5yWZ/OcHRcRMN3H9TH+t90V/j3ENW6C8+igBZFXMJ7G3Pr8Dd13632aLng42wgAAACBeyJvcmlnaW4iOiJodHRwczovL2dvb2dsZXN5bmRpY2F0aW9uLmNvbTo0NDMiLCJmZWF0dXJlIjoiVHJ1c3RUb2tlbnMiLCJleHBpcnkiOjE2NTI3NzQ0MDAsImlzU3ViZG9tYWluIjp0cnVlLCJpc1RoaXJkUGFydHkiOnRydWV9"><meta http-equiv="origin-trial" content="A88BWHFjcawUfKU3lIejLoryXoyjooBXLgWmGh+hNcqMK44cugvsI5YZbNarYvi3roc1fYbHA1AVbhAtuHZflgEAAAB2eyJvcmlnaW4iOiJodHRwczovL2dvb2dsZS5jb206NDQzIiwiZmVhdHVyZSI6IlRydXN0VG9rZW5zIiwiZXhwaXJ5IjoxNjUyNzc0NDAwLCJpc1N1YmRvbWFpbiI6dHJ1ZSwiaXNUaGlyZFBhcnR5Ijp0cnVlfQ=="><meta http-equiv="origin-trial" content="A8FHS1NmdCwGqD9DwOicnHHY+y27kdWfxKa0YHSGDfv0CSpDKRHTQdQmZVPDUdaFWUsxdgVxlwAd6o+dhJykPA0AAACWeyJvcmlnaW4iOiJodHRwczovL2RvdWJsZWNsaWNrLm5ldDo0NDMiLCJmZWF0dXJlIjoiQ29udmVyc2lvbk1lYXN1cmVtZW50IiwiZXhwaXJ5IjoxNjQzMTU1MTk5LCJpc1N1YmRvbWFpbiI6dHJ1ZSwiaXNUaGlyZFBhcnR5Ijp0cnVlLCJ1c2FnZSI6InN1YnNldCJ9"><meta http-equiv="origin-trial" content="A8zdXi6dr1hwXEUjQrYiyYQGlU3557y5QWDnN0Lwgj9ePt66XMEvNkVWOEOWPd7TP9sBQ25X0Q15Lr1Nn4oGFQkAAACceyJvcmlnaW4iOiJodHRwczovL2dvb2dsZXN5bmRpY2F0aW9uLmNvbTo0NDMiLCJmZWF0dXJlIjoiQ29udmVyc2lvbk1lYXN1cmVtZW50IiwiZXhwaXJ5IjoxNjQzMTU1MTk5LCJpc1N1YmRvbWFpbiI6dHJ1ZSwiaXNUaGlyZFBhcnR5Ijp0cnVlLCJ1c2FnZSI6InN1YnNldCJ9"><meta http-equiv="origin-trial" content="A4/Htern2udN9w3yJK9QgWQxQFruxOXsXL7cW60DyCl0EZFGCSme/J33Q/WzF7bBkVvhEWDlcBiUyZaim5CpFQwAAACceyJvcmlnaW4iOiJodHRwczovL2dvb2dsZXRhZ3NlcnZpY2VzLmNvbTo0NDMiLCJmZWF0dXJlIjoiQ29udmVyc2lvbk1lYXN1cmVtZW50IiwiZXhwaXJ5IjoxNjQzMTU1MTk5LCJpc1N1YmRvbWFpbiI6dHJ1ZSwiaXNUaGlyZFBhcnR5Ijp0cnVlLCJ1c2FnZSI6InN1YnNldCJ9"><meta http-equiv="origin-trial" content="AxujKG9INjsZ8/gUq8+dTruNvk7RjZQ1oFhhgQbcTJKDnZfbzSTE81wvC2Hzaf3TW4avA76LTZEMdiedF1vIbA4AAABueyJvcmlnaW4iOiJodHRwczovL2ltYXNkay5nb29nbGVhcGlzLmNvbTo0NDMiLCJmZWF0dXJlIjoiVHJ1c3RUb2tlbnMiLCJleHBpcnkiOjE2NTI3NzQ0MDAsImlzVGhpcmRQYXJ0eSI6dHJ1ZX0="><meta http-equiv="origin-trial" content="Azuce85ORtSnWe1MZDTv68qpaW3iHyfL9YbLRy0cwcCZwVnePnOmkUJlG8HGikmOwhZU22dElCcfrfX2HhrBPAkAAAB7eyJvcmlnaW4iOiJodHRwczovL2RvdWJsZWNsaWNrLm5ldDo0NDMiLCJmZWF0dXJlIjoiVHJ1c3RUb2tlbnMiLCJleHBpcnkiOjE2NTI3NzQ0MDAsImlzU3ViZG9tYWluIjp0cnVlLCJpc1RoaXJkUGFydHkiOnRydWV9"><meta http-equiv="origin-trial" content="A16nvcdeoOAqrJcmjLRpl1I6f3McDD8EfofAYTt/P/H4/AWwB99nxiPp6kA0fXoiZav908Z8etuL16laFPUdfQsAAACBeyJvcmlnaW4iOiJodHRwczovL2dvb2dsZXRhZ3NlcnZpY2VzLmNvbTo0NDMiLCJmZWF0dXJlIjoiVHJ1c3RUb2tlbnMiLCJleHBpcnkiOjE2NTI3NzQ0MDAsImlzU3ViZG9tYWluIjp0cnVlLCJpc1RoaXJkUGFydHkiOnRydWV9"><meta http-equiv="origin-trial" content="AxBHdr0J44vFBQtZUqX9sjiqf5yWZ/OcHRcRMN3H9TH+t90V/j3ENW6C8+igBZFXMJ7G3Pr8Dd13632aLng42wgAAACBeyJvcmlnaW4iOiJodHRwczovL2dvb2dsZXN5bmRpY2F0aW9uLmNvbTo0NDMiLCJmZWF0dXJlIjoiVHJ1c3RUb2tlbnMiLCJleHBpcnkiOjE2NTI3NzQ0MDAsImlzU3ViZG9tYWluIjp0cnVlLCJpc1RoaXJkUGFydHkiOnRydWV9"><meta http-equiv="origin-trial" content="A88BWHFjcawUfKU3lIejLoryXoyjooBXLgWmGh+hNcqMK44cugvsI5YZbNarYvi3roc1fYbHA1AVbhAtuHZflgEAAAB2eyJvcmlnaW4iOiJodHRwczovL2dvb2dsZS5jb206NDQzIiwiZmVhdHVyZSI6IlRydXN0VG9rZW5zIiwiZXhwaXJ5IjoxNjUyNzc0NDAwLCJpc1N1YmRvbWFpbiI6dHJ1ZSwiaXNUaGlyZFBhcnR5Ijp0cnVlfQ=="><meta http-equiv="origin-trial" content="A8FHS1NmdCwGqD9DwOicnHHY+y27kdWfxKa0YHSGDfv0CSpDKRHTQdQmZVPDUdaFWUsxdgVxlwAd6o+dhJykPA0AAACWeyJvcmlnaW4iOiJodHRwczovL2RvdWJsZWNsaWNrLm5ldDo0NDMiLCJmZWF0dXJlIjoiQ29udmVyc2lvbk1lYXN1cmVtZW50IiwiZXhwaXJ5IjoxNjQzMTU1MTk5LCJpc1N1YmRvbWFpbiI6dHJ1ZSwiaXNUaGlyZFBhcnR5Ijp0cnVlLCJ1c2FnZSI6InN1YnNldCJ9"><meta http-equiv="origin-trial" content="A8zdXi6dr1hwXEUjQrYiyYQGlU3557y5QWDnN0Lwgj9ePt66XMEvNkVWOEOWPd7TP9sBQ25X0Q15Lr1Nn4oGFQkAAACceyJvcmlnaW4iOiJodHRwczovL2dvb2dsZXN5bmRpY2F0aW9uLmNvbTo0NDMiLCJmZWF0dXJlIjoiQ29udmVyc2lvbk1lYXN1cmVtZW50IiwiZXhwaXJ5IjoxNjQzMTU1MTk5LCJpc1N1YmRvbWFpbiI6dHJ1ZSwiaXNUaGlyZFBhcnR5Ijp0cnVlLCJ1c2FnZSI6InN1YnNldCJ9"><meta http-equiv="origin-trial" content="A4/Htern2udN9w3yJK9QgWQxQFruxOXsXL7cW60DyCl0EZFGCSme/J33Q/WzF7bBkVvhEWDlcBiUyZaim5CpFQwAAACceyJvcmlnaW4iOiJodHRwczovL2dvb2dsZXRhZ3NlcnZpY2VzLmNvbTo0NDMiLCJmZWF0dXJlIjoiQ29udmVyc2lvbk1lYXN1cmVtZW50IiwiZXhwaXJ5IjoxNjQzMTU1MTk5LCJpc1N1YmRvbWFpbiI6dHJ1ZSwiaXNUaGlyZFBhcnR5Ijp0cnVlLCJ1c2FnZSI6InN1YnNldCJ9"><meta http-equiv="origin-trial" content="AxujKG9INjsZ8/gUq8+dTruNvk7RjZQ1oFhhgQbcTJKDnZfbzSTE81wvC2Hzaf3TW4avA76LTZEMdiedF1vIbA4AAABueyJvcmlnaW4iOiJodHRwczovL2ltYXNkay5nb29nbGVhcGlzLmNvbTo0NDMiLCJmZWF0dXJlIjoiVHJ1c3RUb2tlbnMiLCJleHBpcnkiOjE2NTI3NzQ0MDAsImlzVGhpcmRQYXJ0eSI6dHJ1ZX0="><meta http-equiv="origin-trial" content="Azuce85ORtSnWe1MZDTv68qpaW3iHyfL9YbLRy0cwcCZwVnePnOmkUJlG8HGikmOwhZU22dElCcfrfX2HhrBPAkAAAB7eyJvcmlnaW4iOiJodHRwczovL2RvdWJsZWNsaWNrLm5ldDo0NDMiLCJmZWF0dXJlIjoiVHJ1c3RUb2tlbnMiLCJleHBpcnkiOjE2NTI3NzQ0MDAsImlzU3ViZG9tYWluIjp0cnVlLCJpc1RoaXJkUGFydHkiOnRydWV9"><meta http-equiv="origin-trial" content="A16nvcdeoOAqrJcmjLRpl1I6f3McDD8EfofAYTt/P/H4/AWwB99nxiPp6kA0fXoiZav908Z8etuL16laFPUdfQsAAACBeyJvcmlnaW4iOiJodHRwczovL2dvb2dsZXRhZ3NlcnZpY2VzLmNvbTo0NDMiLCJmZWF0dXJlIjoiVHJ1c3RUb2tlbnMiLCJleHBpcnkiOjE2NTI3NzQ0MDAsImlzU3ViZG9tYWluIjp0cnVlLCJpc1RoaXJkUGFydHkiOnRydWV9"><meta http-equiv="origin-trial" content="AxBHdr0J44vFBQtZUqX9sjiqf5yWZ/OcHRcRMN3H9TH+t90V/j3ENW6C8+igBZFXMJ7G3Pr8Dd13632aLng42wgAAACBeyJvcmlnaW4iOiJodHRwczovL2dvb2dsZXN5bmRpY2F0aW9uLmNvbTo0NDMiLCJmZWF0dXJlIjoiVHJ1c3RUb2tlbnMiLCJleHBpcnkiOjE2NTI3NzQ0MDAsImlzU3ViZG9tYWluIjp0cnVlLCJpc1RoaXJkUGFydHkiOnRydWV9"><meta http-equiv="origin-trial" content="A88BWHFjcawUfKU3lIejLoryXoyjooBXLgWmGh+hNcqMK44cugvsI5YZbNarYvi3roc1fYbHA1AVbhAtuHZflgEAAAB2eyJvcmlnaW4iOiJodHRwczovL2dvb2dsZS5jb206NDQzIiwiZmVhdHVyZSI6IlRydXN0VG9rZW5zIiwiZXhwaXJ5IjoxNjUyNzc0NDAwLCJpc1N1YmRvbWFpbiI6dHJ1ZSwiaXNUaGlyZFBhcnR5Ijp0cnVlfQ=="><meta http-equiv="origin-trial" content="A8FHS1NmdCwGqD9DwOicnHHY+y27kdWfxKa0YHSGDfv0CSpDKRHTQdQmZVPDUdaFWUsxdgVxlwAd6o+dhJykPA0AAACWeyJvcmlnaW4iOiJodHRwczovL2RvdWJsZWNsaWNrLm5ldDo0NDMiLCJmZWF0dXJlIjoiQ29udmVyc2lvbk1lYXN1cmVtZW50IiwiZXhwaXJ5IjoxNjQzMTU1MTk5LCJpc1N1YmRvbWFpbiI6dHJ1ZSwiaXNUaGlyZFBhcnR5Ijp0cnVlLCJ1c2FnZSI6InN1YnNldCJ9"><meta http-equiv="origin-trial" content="A8zdXi6dr1hwXEUjQrYiyYQGlU3557y5QWDnN0Lwgj9ePt66XMEvNkVWOEOWPd7TP9sBQ25X0Q15Lr1Nn4oGFQkAAACceyJvcmlnaW4iOiJodHRwczovL2dvb2dsZXN5bmRpY2F0aW9uLmNvbTo0NDMiLCJmZWF0dXJlIjoiQ29udmVyc2lvbk1lYXN1cmVtZW50IiwiZXhwaXJ5IjoxNjQzMTU1MTk5LCJpc1N1YmRvbWFpbiI6dHJ1ZSwiaXNUaGlyZFBhcnR5Ijp0cnVlLCJ1c2FnZSI6InN1YnNldCJ9"><meta http-equiv="origin-trial" content="A4/Htern2udN9w3yJK9QgWQxQFruxOXsXL7cW60DyCl0EZFGCSme/J33Q/WzF7bBkVvhEWDlcBiUyZaim5CpFQwAAACceyJvcmlnaW4iOiJodHRwczovL2dvb2dsZXRhZ3NlcnZpY2VzLmNvbTo0NDMiLCJmZWF0dXJlIjoiQ29udmVyc2lvbk1lYXN1cmVtZW50IiwiZXhwaXJ5IjoxNjQzMTU1MTk5LCJpc1N1YmRvbWFpbiI6dHJ1ZSwiaXNUaGlyZFBhcnR5Ijp0cnVlLCJ1c2FnZSI6InN1YnNldCJ9"><meta http-equiv="origin-trial" content="AxujKG9INjsZ8/gUq8+dTruNvk7RjZQ1oFhhgQbcTJKDnZfbzSTE81wvC2Hzaf3TW4avA76LTZEMdiedF1vIbA4AAABueyJvcmlnaW4iOiJodHRwczovL2ltYXNkay5nb29nbGVhcGlzLmNvbTo0NDMiLCJmZWF0dXJlIjoiVHJ1c3RUb2tlbnMiLCJleHBpcnkiOjE2NTI3NzQ0MDAsImlzVGhpcmRQYXJ0eSI6dHJ1ZX0="><meta http-equiv="origin-trial" content="Azuce85ORtSnWe1MZDTv68qpaW3iHyfL9YbLRy0cwcCZwVnePnOmkUJlG8HGikmOwhZU22dElCcfrfX2HhrBPAkAAAB7eyJvcmlnaW4iOiJodHRwczovL2RvdWJsZWNsaWNrLm5ldDo0NDMiLCJmZWF0dXJlIjoiVHJ1c3RUb2tlbnMiLCJleHBpcnkiOjE2NTI3NzQ0MDAsImlzU3ViZG9tYWluIjp0cnVlLCJpc1RoaXJkUGFydHkiOnRydWV9"><meta http-equiv="origin-trial" content="A16nvcdeoOAqrJcmjLRpl1I6f3McDD8EfofAYTt/P/H4/AWwB99nxiPp6kA0fXoiZav908Z8etuL16laFPUdfQsAAACBeyJvcmlnaW4iOiJodHRwczovL2dvb2dsZXRhZ3NlcnZpY2VzLmNvbTo0NDMiLCJmZWF0dXJlIjoiVHJ1c3RUb2tlbnMiLCJleHBpcnkiOjE2NTI3NzQ0MDAsImlzU3ViZG9tYWluIjp0cnVlLCJpc1RoaXJkUGFydHkiOnRydWV9"><meta http-equiv="origin-trial" content="AxBHdr0J44vFBQtZUqX9sjiqf5yWZ/OcHRcRMN3H9TH+t90V/j3ENW6C8+igBZFXMJ7G3Pr8Dd13632aLng42wgAAACBeyJvcmlnaW4iOiJodHRwczovL2dvb2dsZXN5bmRpY2F0aW9uLmNvbTo0NDMiLCJmZWF0dXJlIjoiVHJ1c3RUb2tlbnMiLCJleHBpcnkiOjE2NTI3NzQ0MDAsImlzU3ViZG9tYWluIjp0cnVlLCJpc1RoaXJkUGFydHkiOnRydWV9"><meta http-equiv="origin-trial" content="A88BWHFjcawUfKU3lIejLoryXoyjooBXLgWmGh+hNcqMK44cugvsI5YZbNarYvi3roc1fYbHA1AVbhAtuHZflgEAAAB2eyJvcmlnaW4iOiJodHRwczovL2dvb2dsZS5jb206NDQzIiwiZmVhdHVyZSI6IlRydXN0VG9rZW5zIiwiZXhwaXJ5IjoxNjUyNzc0NDAwLCJpc1N1YmRvbWFpbiI6dHJ1ZSwiaXNUaGlyZFBhcnR5Ijp0cnVlfQ=="><meta http-equiv="origin-trial" content="A8FHS1NmdCwGqD9DwOicnHHY+y27kdWfxKa0YHSGDfv0CSpDKRHTQdQmZVPDUdaFWUsxdgVxlwAd6o+dhJykPA0AAACWeyJvcmlnaW4iOiJodHRwczovL2RvdWJsZWNsaWNrLm5ldDo0NDMiLCJmZWF0dXJlIjoiQ29udmVyc2lvbk1lYXN1cmVtZW50IiwiZXhwaXJ5IjoxNjQzMTU1MTk5LCJpc1N1YmRvbWFpbiI6dHJ1ZSwiaXNUaGlyZFBhcnR5Ijp0cnVlLCJ1c2FnZSI6InN1YnNldCJ9"><meta http-equiv="origin-trial" content="A8zdXi6dr1hwXEUjQrYiyYQGlU3557y5QWDnN0Lwgj9ePt66XMEvNkVWOEOWPd7TP9sBQ25X0Q15Lr1Nn4oGFQkAAACceyJvcmlnaW4iOiJodHRwczovL2dvb2dsZXN5bmRpY2F0aW9uLmNvbTo0NDMiLCJmZWF0dXJlIjoiQ29udmVyc2lvbk1lYXN1cmVtZW50IiwiZXhwaXJ5IjoxNjQzMTU1MTk5LCJpc1N1YmRvbWFpbiI6dHJ1ZSwiaXNUaGlyZFBhcnR5Ijp0cnVlLCJ1c2FnZSI6InN1YnNldCJ9"><meta http-equiv="origin-trial" content="A4/Htern2udN9w3yJK9QgWQxQFruxOXsXL7cW60DyCl0EZFGCSme/J33Q/WzF7bBkVvhEWDlcBiUyZaim5CpFQwAAACceyJvcmlnaW4iOiJodHRwczovL2dvb2dsZXRhZ3NlcnZpY2VzLmNvbTo0NDMiLCJmZWF0dXJlIjoiQ29udmVyc2lvbk1lYXN1cmVtZW50IiwiZXhwaXJ5IjoxNjQzMTU1MTk5LCJpc1N1YmRvbWFpbiI6dHJ1ZSwiaXNUaGlyZFBhcnR5Ijp0cnVlLCJ1c2FnZSI6InN1YnNldCJ9"><link rel="stylesheet" type="text/css" href="./Алгоритм DFS («Depth-first search» или «Поиск в глубину»)_files/prettify.css"><script charset="utf-8" src="./Алгоритм DFS («Depth-first search» или «Поиск в глубину»)_files/f8af04246520396c3722.js" crossorigin="anonymous" importance="high"></script><script charset="utf-8" src="./Алгоритм DFS («Depth-first search» или «Поиск в глубину»)_files/999b92812ceab9de3d7c.js" crossorigin="anonymous" importance="high"></script><script async="" crossorigin="anonymous" src="./Алгоритм DFS («Depth-first search» или «Поиск в глубину»)_files/host.js"></script><link rel="preconnect" href="https://yastatic.net/"><link rel="preconnect" href="https://avatars.mds.yandex.net/"><link rel="preconnect" href="https://mc.yandex.ru/"><meta id="https://yastatic.net/partner-code-bundles/57153/context_static.js"><link rel="preconnect" href="https://ads.adfox.ru/"><script charset="utf-8" src="./Алгоритм DFS («Depth-first search» или «Поиск в глубину»)_files/b260d1d104887197a0a2.js" crossorigin="anonymous" importance="high"></script><link rel="preload" href="./Алгоритм DFS («Depth-first search» или «Поиск в глубину»)_files/f(2).txt" as="script"><script type="text/javascript" src="./Алгоритм DFS («Depth-first search» или «Поиск в глубину»)_files/f(2).txt"></script><link rel="preload" href="./Алгоритм DFS («Depth-first search» или «Поиск в глубину»)_files/f(3).txt" as="script"><script type="text/javascript" src="./Алгоритм DFS («Depth-first search» или «Поиск в глубину»)_files/f(3).txt"></script><style nonce="">#b5796c3e1f{width:1px;height:1px;position:relative;}</style><style nonce="">#id2817{width:1px;height:1px;top:0px;left:0px;position:absolute;}</style></head><body class="body"><div class="modal fade" id="menuModal" tabindex="-1" aria-hidden="true"><div class="modal-dialog modal-lg w-auto modal-content"><div class="modal-header"><span>Выбрать раздел</span><span class="mdi mdi-24px mdi-window-close mdi-0 pointer" data-dismiss="modal" aria-label="Close"></span></div><div class="modal-body"><a class="btn btn-dark btn-menu" href="https://evileg.com/ru/knowledge/"><div class="btn-menu-body"><div class="btn-menu-center"><div class="btn-menu-icon-offset"><span class="mdi mdi-36px mdi-newspaper mdi-0"></span></div><small>Статьи</small></div></div></a><a class="btn btn-dark btn-menu" href="https://evileg.com/ru/forum/"><div class="btn-menu-body"><div class="btn-menu-center"><div class="btn-menu-icon-offset"><span class="mdi mdi-36px mdi-forum mdi-0"></span></div><small>Форум</small></div></div></a><a class="btn btn-dark btn-menu" href="https://evileg.com/ru/tests/"><div class="btn-menu-body"><div class="btn-menu-center"><div class="btn-menu-icon-offset"><span class="mdi mdi-36px mdi-format-list-checks mdi-0"></span></div><small>Тесты</small></div></div></a><a class="btn btn-dark btn-menu" href="https://evileg.com/ru/vacancy/"><div class="btn-menu-body"><div class="btn-menu-center"><div class="btn-menu-icon-offset"><span class="mdi mdi-36px mdi-briefcase mdi-0"></span></div><small>Вакансии</small></div></div></a><a class="btn btn-dark btn-menu" href="https://evileg.com/ru/social_bookmarks/"><div class="btn-menu-body"><div class="btn-menu-center"><div class="btn-menu-icon-offset"><span class="mdi mdi-36px mdi-bookmark mdi-0"></span></div><small>Закладки</small></div></div></a><a class="btn btn-dark btn-menu" href="https://evileg.com/ru/forum/ideas/"><div class="btn-menu-body"><div class="btn-menu-center"><div class="btn-menu-icon-offset"><span class="mdi mdi-36px mdi-lightbulb-on mdi-0"></span></div><small>Идеи</small></div></div></a><a class="btn btn-dark btn-menu" href="https://evileg.com/ru/sharecode/"><div class="btn-menu-body"><div class="btn-menu-center"><div class="btn-menu-icon-offset"><span class="mdi mdi-36px mdi-share-variant mdi-0"></span></div><small>Расшарить код</small></div></div></a><a class="btn btn-dark btn-menu" href="https://evileg.com/ru/companies/"><div class="btn-menu-body"><div class="btn-menu-center"><div class="btn-menu-icon-offset"><span class="mdi mdi-36px mdi-office-building mdi-0"></span></div><small>Компании</small></div></div></a><a class="btn btn-dark btn-menu" href="https://evileg.com/ru/users/"><div class="btn-menu-body"><div class="btn-menu-center"><div class="btn-menu-icon-offset"><span class="mdi mdi-36px mdi-account-group mdi-0"></span></div><small>Пользователи</small></div></div></a></div></div></div><div id="drawer" class="drawer drawer-closed box-shadow"><nav class="mb-2 drawer-nav"><div class="p-3"><form class="m-0" action="https://evileg.com/ru/accounts/login/" method="post"><input type="hidden" name="csrfmiddlewaretoken" value="YPhmdOEARMXBmRqWTBozBLYvLSekfFIp7mm1zW4LmsKmv8KCNotKhr7UsQN38ZAb"><div class="form-group"><label for="id_username">Имя пользователя</label><input type="text" name="username" autofocus="" autocapitalize="none" autocomplete="username" maxlength="150" class="form-control" placeholder="Имя пользователя или email" title="" required="" id="id_username"></div><div class="form-group"><label for="id_password">Пароль</label><input type="password" name="password" autocomplete="current-password" class="form-control" placeholder="Пароль" title="" required="" id="id_password"></div><button type="submit" class="btn btn-sm btn-primary btn-raised mdi mdi-login">Войти</button><div class="mt-2 mb-1"><small><a href="https://evileg.com/ru/accounts/register/">Зарегистрироваться</a> -
            <a href="https://evileg.com/ru/accounts/forgot/">Забыли пароль?</a> -
            <a href="https://evileg.com/ru/accounts/activate/">Активировать аккаунт</a></small></div><small class="text-secondary">Войти с помощью социальной сети</small><div style="line-height: initial;"><a href="https://evileg.com/login/vk-oauth2/" class="mdi mdi-vk-box mdi-48px vk-color"></a><a href="https://evileg.com/login/google-oauth2/" class="mdi mdi-google-plus-box mdi-48px google-color"></a><a href="https://evileg.com/login/facebook/" class="mdi mdi-facebook-box mdi-48px fb-color"></a><a href="https://evileg.com/login/github/" class="mdi mdi-github-box mdi-48px github-color"></a></div></form></div><form action="https://evileg.com/ru/search/" class="m-0 p-0 border-bottom border-top" method="get"><div class="input-group"><input id="search" name="search" type="search" class="form-control px-3 border-0" placeholder="Поиск..."></div></form><div class="drawer_items_list border-0"><a href="https://evileg.com/ru/sharecode/create/"><span>Расшарить код</span></a><a href="https://evileg.com/ru/knowledge/article/add/"><span>Написать статью</span></a><a href="https://evileg.com/ru/forum/create_topic/"><span>Задать вопрос</span></a><a href="https://evileg.com/ru/tests/"><span>Пройти тест</span></a></div></nav></div><header class="fixed-top header box-shadow"><nav class="navbar navbar-expand navbar-light bg-white"><ul class="navbar-nav mr-0"><button class="navbar-toggler mr-4 d-block d-xl-none border" type="button" onclick="$(&#39;body&#39;).toggleDrawer();"><span class="navbar-toggler-icon"></span></button><li class="nav-item mr-auto mr-sm-0"><a href="https://evileg.com/ru/" class="navbar-brand">EVILEG</a></li></ul><div class="navbar-nav d-none d-sm-flex flex-wrap overflow-hidden"><a class="nav-link" href="https://evileg.com/ru/knowledge/">Статьи</a><a class="nav-link" href="https://evileg.com/ru/forum/">Форум</a><a class="nav-link" href="https://evileg.com/ru/tests/">Тесты</a><a class="nav-link" href="https://evileg.com/ru/vacancy/">Вакансии</a><a class="nav-link" href="https://evileg.com/ru/social_bookmarks/">Закладки</a><a class="nav-link" href="https://evileg.com/ru/forum/ideas/">Идеи</a><a class="nav-link" href="https://evileg.com/ru/sharecode/">Расшарить код</a><a class="nav-link" href="https://evileg.com/ru/companies/">Компании</a><a class="nav-link" href="https://evileg.com/ru/users/">Пользователи</a></div><ul class="navbar-nav ml-auto"><li class="nav-item mr-1"><a class="nav-link mdi mdi-36px mdi-apps p-0 pointer" style="margin-top: -6px; margin-bottom: -14px;" data-toggle="modal" data-target="#menuModal"></a></li><li class="nav-item dropdown"><a class="nav-link dropdown-toggle border lang-btn" href="https://evileg.com/ru/post/494/#" id="navbarDropdown" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">ru</a><div class="dropdown-menu dropdown-menu-right" aria-labelledby="navbarDropdown"><a class="dropdown-item" href="https://evileg.com/lang/ru/">Русский</a><a class="dropdown-item" href="https://evileg.com/lang/uk/">Українська</a><a class="dropdown-item" href="https://evileg.com/lang/en/">English</a><a class="dropdown-item" href="https://evileg.com/lang/de/">Deutsch</a></div></li></ul></nav></header><main class="container-fluid px-0 mx-0 row" style="height: auto !important;"><div class="col-12 col-lg-9 px-0 border-right border-bottom" style="height: auto !important; min-height: 0px !important;"><ul class="breadcrumb bg-light"><li class="breadcrumb-item"><a href="https://evileg.com/ru/"><span class="mdi mdi-home mdi-0"><span class="d-none">EVILEG</span></span></a></li><li class="breadcrumb-item"><a href="https://evileg.com/ru/knowledge/">Статьи</a></li><li class="breadcrumb-item"><a href="https://evileg.com/ru/knowledge/algorithms/">Алгоритмы</a></li><li class="breadcrumb-item active">Алгоритм DFS («Depth-first search» или «Поиск в глубину»)</li></ul><script type="application/ld+json">{"@context": "http://schema.org", "@type": "BreadcrumbList", "itemListElement": [{"@type": "ListItem", "position": 1, "item": {"@type": "Thing", "@id": "/ru/", "name": "EVILEG"}}, {"@type": "ListItem", "position": 2, "item": {"@type": "Thing", "@id": "/ru/knowledge/", "name": "Статьи"}}, {"@type": "ListItem", "position": 3, "item": {"@type": "Thing", "@id": "/ru/knowledge/algorithms/", "name": "Алгоритмы"}}, {"@type": "ListItem", "position": 4, "item": {"@type": "Thing", "@id": "/ru/post/494/", "name": "Алгоритм DFS («Depth-first search» или «Поиск в глубину»)"}}]}</script><div style="height: auto !important;"><article style="height: auto !important;"><div itemprop="publisher" itemscope="" itemtype="https://schema.org/Organization"><div itemprop="logo" itemscope="" itemtype="https://schema.org/ImageObject"><link itemprop="image" href="https://evileg.com/static/images/favicons/apple-touch-icon-152x152.png"><link itemprop="url" href="https://evileg.com/static/images/favicons/apple-touch-icon-152x152.png"><meta itemprop="width" content="152"><meta itemprop="height" content="152"></div><meta itemprop="name" content="EVILEG"><meta itemprop="address" content="EVILEG"><meta itemprop="telephone" content="-"><link itemprop="url" href="https://evileg.com/"></div><link itemprop="mainEntityOfPage" itemscope="" href="https://evileg.com/ru/post/494/"><meta itemprop="commentCount" content="0"><meta itemprop="articleSection" content="Алгоритмы"><div itemscope="" itemprop="author" itemtype="https://schema.org/Person"><meta itemprop="name" content="mafulechka"><link itemprop="url" content="/ru/users/mafulechka/"></div><meta itemprop="url" content="/ru/post/494/"><meta itemprop="accessMode" content="textual"><meta itemprop="wordCount" content="1076"><meta itemprop="datePublished" content="17 июня 2019 г. 12:45"><meta itemprop="dateModified" content="19 июня 2020 г. 3:02"><div itemprop="interactionStatistic" itemscope="" itemtype="https://schema.org/InteractionCounter"><meta itemprop="interactionType" content="https://schema.org/BookmarkAction"><meta itemprop="userInteractionCount" content="1"></div><div itemprop="interactionStatistic" itemscope="" itemtype="https://schema.org/InteractionCounter"><meta itemprop="interactionType" content="https://schema.org/LikeAction"><meta itemprop="userInteractionCount" content="2"></div><div itemprop="interactionStatistic" itemscope="" itemtype="https://schema.org/InteractionCounter"><meta itemprop="interactionType" content="https://schema.org/DislikeAction"><meta itemprop="userInteractionCount" content="0"></div><meta itemprop="keywords" content="Tree,Дерево,Алгоритм"><div class="card border-bottom" style="height: auto !important;"><div class="card-body" style="height: auto !important;"><div class="media mb-2"><a class="mr-3 text-decoration-none" href="https://evileg.com/ru/users/mafulechka/"><div class="m-0 p-0 position-relative"><div class="bg-white avatar-3 rounded-circle m-0 box-shadow"><img loading="lazy" class="avatar-3 rounded-circle m-0" src="./Алгоритм DFS («Depth-first search» или «Поиск в глубину»)_files/avatar.jpg"></div></div></a><div class="media-body"><a href="https://evileg.com/ru/users/mafulechka/" class="mr-2 text-truncate d-block">mafulechka</a><small class="text-muted text-nowrap">17 июня 2019 г. 12:45</small></div></div><h1 itemprop="headline">Алгоритм DFS («Depth-first search» или «Поиск в глубину»)</h1><div><p><a href="https://evileg.com/ru/search/?search=%23Tree">Tree</a>, <a href="https://evileg.com/ru/search/?search=%23%D0%94%D0%B5%D1%80%D0%B5%D0%B2%D0%BE">Дерево</a>, <a href="https://evileg.com/ru/search/?search=%23%D0%90%D0%BB%D0%B3%D0%BE%D1%80%D0%B8%D1%82%D0%BC">Алгоритм</a></p></div><div itemprop="articleBody" class="e-text" style="height: auto !important;"><p><strong>
   Обход
  </strong>
  означает посещение всех узлов графа.
  <strong>
   «Обход в глубину» или «Поиск в глубину»
  </strong>
  - это рекурсивный алгоритм поиска всех вершин графа или древовидной структуры данных. В этой статье, с помощью приведенных ниже примеров, вы узнаете: алгоритм DFS, псевдокод DFS и код алгоритма «поиска в глубину» с реализацией в программах на C ++, C, Java и Python.
 </p><div class="card border mb-3"><div class="card-header">Содержание</div><div class="card-body"><ol class="list-unstyled mb-0"><li><span>1. </span><span><a href="https://evileg.com/ru/post/494/#header_%D0%90%D0%BB%D0%B3%D0%BE%D1%80%D0%B8%D1%82%D0%BC_DFS">Алгоритм DFS</a></span></li><li><span>2. </span><span><a href="https://evileg.com/ru/post/494/#header_%D0%9F%D1%80%D0%B8%D0%BC%D0%B5%D1%80_DFS">Пример DFS</a></span></li><li><span>3. </span><span><a href="https://evileg.com/ru/post/494/#header_%D0%9F%D1%81%D0%B5%D0%B2%D0%B4%D0%BE%D0%BA%D0%BE%D0%B4_DFS_(%D1%80%D0%B5%D0%BA%D1%83%D1%80%D1%81%D0%B8%D0%B2%D0%BD%D0%B0%D1%8F_%D1%80%D0%B5%D0%B0%D0%BB%D0%B8%D0%B7%D0%B0%D1%86%D0%B8%D1%8F)">Псевдокод DFS (рекурсивная реализация)</a></span></li><li><span>4. </span><span><a href="https://evileg.com/ru/post/494/#header_%D0%9A%D0%BE%D0%B4_DFS">Код DFS</a></span></li><li><span>5. </span><span><a href="https://evileg.com/ru/post/494/#header_DFS_%D0%B2_C">DFS в C</a></span></li><li><span>6. </span><span><a href="https://evileg.com/ru/post/494/#header_Depth_First_Search_(DFS)_%D0%B2_C++">Depth First Search (DFS) в C++</a></span></li><li><span>7. </span><span><a href="https://evileg.com/ru/post/494/#header_DFS_Java_%D0%BA%D0%BE%D0%B4_(Java_code)">DFS Java код (Java code)</a></span></li><li><span>8. </span><span><a href="https://evileg.com/ru/post/494/#header_DFS_%D0%B2_Python">DFS в Python</a></span></li></ol></div></div><script async="" src="./Алгоритм DFS («Depth-first search» или «Поиск в глубину»)_files/f(4).txt"></script><!-- Evileg COM Header --><ins class="adsbygoogle" style="display: block; height: 0px;" data-ad-client="ca-pub-8877856398367795" data-ad-slot="4753134862" data-ad-format="auto" data-full-width-responsive="true" data-adsbygoogle-status="done" data-ad-status="unfilled"><ins id="aswift_0_expand" tabindex="0" title="Advertisement" aria-label="Advertisement" style="border: none; height: 0px; width: 793px; margin: 0px; padding: 0px; position: relative; visibility: visible; background-color: transparent; display: inline-table;"><ins id="aswift_0_anchor" style="border: none; height: 0px; width: 793px; margin: 0px; padding: 0px; position: relative; visibility: visible; background-color: transparent; display: block; overflow: hidden; opacity: 0;"><iframe id="aswift_0" name="aswift_0" style="left: 0px; position: absolute; top: 0px; border: 0px; width: 793px; height: 0px;" sandbox="allow-forms allow-popups allow-popups-to-escape-sandbox allow-same-origin allow-scripts allow-top-navigation-by-user-activation" width="793" height="0" frameborder="0" marginwidth="0" marginheight="0" vspace="0" hspace="0" allowtransparency="true" scrolling="no" src="./Алгоритм DFS («Depth-first search» или «Поиск в глубину»)_files/ads.html" data-google-container-id="a!1" data-google-query-id="CIKhlor0-fYCFcarmgod1rgIiw" data-load-complete="true"></iframe></ins></ins></ins><script>
     (adsbygoogle = window.adsbygoogle || []).push({});
</script><p><span class="small">ADS</span></p><h2><a class="anchor" id="header_Алгоритм_DFS"></a>
  Алгоритм DFS
 </h2><p>
  Стандартная реализация DFS помещает каждую вершину графа в одну из двух категорий:
 </p><ol><li>
   Посещенные.
  </li><li>
   Не посещенные.
  </li></ol><p><em>
   Цель алгоритма
  </em>
  - пометить каждую вершину, как посещенную, избегая циклов.
 </p><p>
  Алгоритм DFS работает следующим образом:
 </p><ol><li>
   Начните с размещения любой вершины графа на вершине стека.
  </li><li>
   Возьмите верхний элемент стека и добавьте его в список посещенных.
  </li><li>
   Создайте список смежных узлов этой вершины. Добавьте те, которых нет в списке посещенных, в начало стека.
  </li><li>
   Продолжайте повторять шаги 2 и 3, пока стек не станет пустым.
  </li></ol><h2><a class="anchor" id="header_Пример_DFS"></a>
  Пример DFS
 </h2><p>
  Давайте посмотрим, как алгоритм «поиска в глубину» работает на примере. Мы используем неориентированный граф с 5 вершинами.
 </p><p><a href="https://evileg.com/users/mafulechka/albums/photo/656/"><img alt="" class="img-fluid" loading="lazy" src="./Алгоритм DFS («Depth-first search» или «Поиск в глубину»)_files/photo_Fh0D25r.jpg"></a></p><p>
  Мы начинаем с вершины 0, алгоритм DFS начинается с помещения его в список посещенных и размещения всех смежных вершин в стеке.
 </p><p><a href="https://evileg.com/users/mafulechka/albums/photo/657/"><img alt="" class="img-fluid" loading="lazy" src="./Алгоритм DFS («Depth-first search» или «Поиск в глубину»)_files/photo_wcFInXJ.jpg"></a></p><p>
  Затем мы посещаем элемент в верхней части стека, то есть 1, и переходим к смежным узлам. Так как 0 мы уже посетили, вместо этого посещаем 2.
 </p><p><a href="https://evileg.com/users/mafulechka/albums/photo/658/"><img alt="" class="img-fluid" loading="lazy" src="./Алгоритм DFS («Depth-first search» или «Поиск в глубину»)_files/photo_2hCTc9D.jpg"></a></p><p>
  У вершины 2 есть не посещенная смежная вершина 4, поэтому мы добавляем ее в верхнюю часть стека и посещаем.
 </p><p><a href="https://evileg.com/users/mafulechka/albums/photo/659/"><img alt="" class="img-fluid" loading="lazy" src="./Алгоритм DFS («Depth-first search» или «Поиск в глубину»)_files/photo_aUdGYed.jpg"></a></p><p><a href="https://evileg.com/users/mafulechka/albums/photo/660/"><img alt="" class="img-fluid" loading="lazy" src="./Алгоритм DFS («Depth-first search» или «Поиск в глубину»)_files/photo_4yyqvZO.jpg"></a></p><p>
  После того, как мы посетим последний элемент 3, у него нет не посещенных смежных узлов. На этом мы завершим первый «обход в глубину» графа.
 </p><p><a href="https://evileg.com/users/mafulechka/albums/photo/661/"><img alt="" class="img-fluid" loading="lazy" src="./Алгоритм DFS («Depth-first search» или «Поиск в глубину»)_files/photo_k1RKQuK.jpg"></a></p><h2><a class="anchor" id="header_Псевдокод_DFS_(рекурсивная_реализация)"></a>
  Псевдокод DFS (рекурсивная реализация)
 </h2><p>
  Псевдокод для DFS показан ниже. Обратите внимание, что в функции
  <strong>
   init()
  </strong>
  мы запускаем функцию DFS на каждом узле. Это связано с тем, что граф может иметь две разные несвязанные части, поэтому, чтобы убедиться, что мы покрываем каждую вершину, мы также можем запустить алгоритм DFS на каждом узле.
 </p><pre><pre class="lang-cpp prettyprint linenums prettyprinted" style=""><ol class="linenums"><li class="L0"><span class="pln">DFS</span><span class="pun">(</span><span class="pln">G</span><span class="pun">,</span><span class="pln"> u</span><span class="pun">)</span></li><li class="L1"><span class="pln">    u</span><span class="pun">.</span><span class="pln">visited </span><span class="pun">=</span><span class="pln"> </span><span class="kwd">true</span></li><li class="L2"><span class="pln">    </span><span class="kwd">for</span><span class="pln"> each v </span><span class="pun">∈</span><span class="pln"> G</span><span class="pun">.</span><span class="typ">Adj</span><span class="pun">[</span><span class="pln">u</span><span class="pun">]</span></li><li class="L3"><span class="pln">        </span><span class="kwd">if</span><span class="pln"> v</span><span class="pun">.</span><span class="pln">visited </span><span class="pun">==</span><span class="pln"> </span><span class="kwd">false</span></li><li class="L4"><span class="pln">            DFS</span><span class="pun">(</span><span class="pln">G</span><span class="pun">,</span><span class="pln">v</span><span class="pun">)</span></li><li class="L5"><span class="pln">&nbsp;</span></li><li class="L6"><span class="pln">init</span><span class="pun">()</span><span class="pln"> </span><span class="pun">{</span></li><li class="L7"><span class="pln">    </span><span class="typ">For</span><span class="pln"> each u </span><span class="pun">∈</span><span class="pln"> G</span></li><li class="L8"><span class="pln">        u</span><span class="pun">.</span><span class="pln">visited </span><span class="pun">=</span><span class="pln"> </span><span class="kwd">false</span></li><li class="L9"><span class="pln">     </span><span class="typ">For</span><span class="pln"> each u </span><span class="pun">∈</span><span class="pln"> G</span></li><li class="L0"><span class="pln">       DFS</span><span class="pun">(</span><span class="pln">G</span><span class="pun">,</span><span class="pln"> u</span><span class="pun">)</span></li><li class="L1"><span class="pun">}</span></li></ol></pre></pre><h2><a class="anchor" id="header_Код_DFS"></a>
  Код DFS
 </h2><p>
  Код для алгоритма «поиска в глубину» с примером показан ниже. Код был упрощен, поэтому мы можем сосредоточиться на алгоритме, а не на других деталях.
 </p><h2><a class="anchor" id="header_DFS_в_C"></a>
  DFS в C
 </h2><pre><pre class="lang-cpp prettyprint linenums prettyprinted" style=""><ol class="linenums"><li class="L0"><span class="com">#include</span><span class="pln"> </span><span class="str">&lt;stdio.h&gt;</span></li><li class="L1"><span class="com">#include</span><span class="pln"> </span><span class="str">&lt;stdlib.h&gt;</span></li><li class="L2"><span class="pln">&nbsp;</span></li><li class="L3"><span class="kwd">struct</span><span class="pln"> node</span></li><li class="L4"><span class="pun">{</span></li><li class="L5"><span class="pln">    </span><span class="typ">int</span><span class="pln"> vertex</span><span class="pun">;</span></li><li class="L6"><span class="pln">    </span><span class="kwd">struct</span><span class="pln"> node</span><span class="pun">*</span><span class="pln"> next</span><span class="pun">;</span></li><li class="L7"><span class="pun">};</span></li><li class="L8"><span class="pln">&nbsp;</span></li><li class="L9"><span class="kwd">struct</span><span class="pln"> node</span><span class="pun">*</span><span class="pln"> createNode</span><span class="pun">(</span><span class="typ">int</span><span class="pln"> v</span><span class="pun">);</span></li><li class="L0"><span class="pln">&nbsp;</span></li><li class="L1"><span class="kwd">struct</span><span class="pln"> </span><span class="typ">Graph</span></li><li class="L2"><span class="pun">{</span></li><li class="L3"><span class="pln">    </span><span class="typ">int</span><span class="pln"> numVertices</span><span class="pun">;</span></li><li class="L4"><span class="pln">    </span><span class="typ">int</span><span class="pun">*</span><span class="pln"> visited</span><span class="pun">;</span></li><li class="L5"><span class="pln">    </span><span class="kwd">struct</span><span class="pln"> node</span><span class="pun">**</span><span class="pln"> adjLists</span><span class="pun">;</span><span class="pln"> </span><span class="com">// we need int** to store a two dimensional array. Similary, we need struct node** to store an array of Linked lists</span></li><li class="L6"><span class="pun">};</span></li><li class="L7"><span class="pln">&nbsp;</span></li><li class="L8"><span class="kwd">struct</span><span class="pln"> </span><span class="typ">Graph</span><span class="pun">*</span><span class="pln"> createGraph</span><span class="pun">(</span><span class="typ">int</span><span class="pun">);</span></li><li class="L9"><span class="kwd">void</span><span class="pln"> addEdge</span><span class="pun">(</span><span class="kwd">struct</span><span class="pln"> </span><span class="typ">Graph</span><span class="pun">*,</span><span class="pln"> </span><span class="typ">int</span><span class="pun">,</span><span class="pln"> </span><span class="typ">int</span><span class="pun">);</span></li><li class="L0"><span class="kwd">void</span><span class="pln"> printGraph</span><span class="pun">(</span><span class="kwd">struct</span><span class="pln"> </span><span class="typ">Graph</span><span class="pun">*);</span></li><li class="L1"><span class="kwd">void</span><span class="pln"> DFS</span><span class="pun">(</span><span class="kwd">struct</span><span class="pln"> </span><span class="typ">Graph</span><span class="pun">*,</span><span class="pln"> </span><span class="typ">int</span><span class="pun">);</span></li><li class="L2"><span class="pln">&nbsp;</span></li><li class="L3"><span class="pln">&nbsp;</span></li><li class="L4"><span class="typ">int</span><span class="pln"> main</span><span class="pun">()</span></li><li class="L5"><span class="pun">{</span></li><li class="L6"><span class="pln">&nbsp;</span></li><li class="L7"><span class="pln">    </span><span class="kwd">struct</span><span class="pln"> </span><span class="typ">Graph</span><span class="pun">*</span><span class="pln"> graph </span><span class="pun">=</span><span class="pln"> createGraph</span><span class="pun">(</span><span class="lit">4</span><span class="pun">);</span></li><li class="L8"><span class="pln">    addEdge</span><span class="pun">(</span><span class="pln">graph</span><span class="pun">,</span><span class="pln"> </span><span class="lit">0</span><span class="pun">,</span><span class="pln"> </span><span class="lit">1</span><span class="pun">);</span></li><li class="L9"><span class="pln">    addEdge</span><span class="pun">(</span><span class="pln">graph</span><span class="pun">,</span><span class="pln"> </span><span class="lit">0</span><span class="pun">,</span><span class="pln"> </span><span class="lit">2</span><span class="pun">);</span></li><li class="L0"><span class="pln">    addEdge</span><span class="pun">(</span><span class="pln">graph</span><span class="pun">,</span><span class="pln"> </span><span class="lit">1</span><span class="pun">,</span><span class="pln"> </span><span class="lit">2</span><span class="pun">);</span></li><li class="L1"><span class="pln">    addEdge</span><span class="pun">(</span><span class="pln">graph</span><span class="pun">,</span><span class="pln"> </span><span class="lit">2</span><span class="pun">,</span><span class="pln"> </span><span class="lit">3</span><span class="pun">);</span></li><li class="L2"><span class="pln">&nbsp;</span></li><li class="L3"><span class="pln">    printGraph</span><span class="pun">(</span><span class="pln">graph</span><span class="pun">);</span></li><li class="L4"><span class="pln">&nbsp;</span></li><li class="L5"><span class="pln">    DFS</span><span class="pun">(</span><span class="pln">graph</span><span class="pun">,</span><span class="pln"> </span><span class="lit">2</span><span class="pun">);</span></li><li class="L6"><span class="pln">&nbsp;</span></li><li class="L7"><span class="pln">    </span><span class="kwd">return</span><span class="pln"> </span><span class="lit">0</span><span class="pun">;</span></li><li class="L8"><span class="pun">}</span></li><li class="L9"><span class="pln">&nbsp;</span></li><li class="L0"><span class="kwd">void</span><span class="pln"> DFS</span><span class="pun">(</span><span class="kwd">struct</span><span class="pln"> </span><span class="typ">Graph</span><span class="pun">*</span><span class="pln"> graph</span><span class="pun">,</span><span class="pln"> </span><span class="typ">int</span><span class="pln"> vertex</span><span class="pun">)</span><span class="pln"> </span><span class="pun">{</span></li><li class="L1"><span class="pln">        </span><span class="kwd">struct</span><span class="pln"> node</span><span class="pun">*</span><span class="pln"> adjList </span><span class="pun">=</span><span class="pln"> graph</span><span class="pun">-&gt;</span><span class="pln">adjLists</span><span class="pun">[</span><span class="pln">vertex</span><span class="pun">];</span></li><li class="L2"><span class="pln">        </span><span class="kwd">struct</span><span class="pln"> node</span><span class="pun">*</span><span class="pln"> temp </span><span class="pun">=</span><span class="pln"> adjList</span><span class="pun">;</span></li><li class="L3"><span class="pln">&nbsp;</span></li><li class="L4"><span class="pln">        graph</span><span class="pun">-&gt;</span><span class="pln">visited</span><span class="pun">[</span><span class="pln">vertex</span><span class="pun">]</span><span class="pln"> </span><span class="pun">=</span><span class="pln"> </span><span class="lit">1</span><span class="pun">;</span></li><li class="L5"><span class="pln">        printf</span><span class="pun">(</span><span class="str">"Visited %d \n"</span><span class="pun">,</span><span class="pln"> vertex</span><span class="pun">);</span></li><li class="L6"><span class="pln">&nbsp;</span></li><li class="L7"><span class="pln">        </span><span class="kwd">while</span><span class="pun">(</span><span class="pln">temp</span><span class="pun">!=</span><span class="pln">NULL</span><span class="pun">)</span><span class="pln"> </span><span class="pun">{</span></li><li class="L8"><span class="pln">            </span><span class="typ">int</span><span class="pln"> connectedVertex </span><span class="pun">=</span><span class="pln"> temp</span><span class="pun">-&gt;</span><span class="pln">vertex</span><span class="pun">;</span></li><li class="L9"><span class="pln">&nbsp;</span></li><li class="L0"><span class="pln">            </span><span class="kwd">if</span><span class="pun">(</span><span class="pln">graph</span><span class="pun">-&gt;</span><span class="pln">visited</span><span class="pun">[</span><span class="pln">connectedVertex</span><span class="pun">]</span><span class="pln"> </span><span class="pun">==</span><span class="pln"> </span><span class="lit">0</span><span class="pun">)</span><span class="pln"> </span><span class="pun">{</span></li><li class="L1"><span class="pln">                DFS</span><span class="pun">(</span><span class="pln">graph</span><span class="pun">,</span><span class="pln"> connectedVertex</span><span class="pun">);</span></li><li class="L2"><span class="pln">            </span><span class="pun">}</span></li><li class="L3"><span class="pln">            temp </span><span class="pun">=</span><span class="pln"> temp</span><span class="pun">-&gt;</span><span class="pln">next</span><span class="pun">;</span></li><li class="L4"><span class="pln">        </span><span class="pun">}</span><span class="pln">       </span></li><li class="L5"><span class="pun">}</span></li><li class="L6"><span class="pln">&nbsp;</span></li><li class="L7"><span class="pln">&nbsp;</span></li><li class="L8"><span class="kwd">struct</span><span class="pln"> node</span><span class="pun">*</span><span class="pln"> createNode</span><span class="pun">(</span><span class="typ">int</span><span class="pln"> v</span><span class="pun">)</span></li><li class="L9"><span class="pun">{</span></li><li class="L0"><span class="pln">    </span><span class="kwd">struct</span><span class="pln"> node</span><span class="pun">*</span><span class="pln"> newNode </span><span class="pun">=</span><span class="pln"> malloc</span><span class="pun">(</span><span class="kwd">sizeof</span><span class="pun">(</span><span class="kwd">struct</span><span class="pln"> node</span><span class="pun">));</span></li><li class="L1"><span class="pln">    newNode</span><span class="pun">-&gt;</span><span class="pln">vertex </span><span class="pun">=</span><span class="pln"> v</span><span class="pun">;</span></li><li class="L2"><span class="pln">    newNode</span><span class="pun">-&gt;</span><span class="pln">next </span><span class="pun">=</span><span class="pln"> NULL</span><span class="pun">;</span></li><li class="L3"><span class="pln">    </span><span class="kwd">return</span><span class="pln"> newNode</span><span class="pun">;</span></li><li class="L4"><span class="pun">}</span></li><li class="L5"><span class="pln">&nbsp;</span></li><li class="L6"><span class="kwd">struct</span><span class="pln"> </span><span class="typ">Graph</span><span class="pun">*</span><span class="pln"> createGraph</span><span class="pun">(</span><span class="typ">int</span><span class="pln"> vertices</span><span class="pun">)</span></li><li class="L7"><span class="pun">{</span></li><li class="L8"><span class="pln">    </span><span class="kwd">struct</span><span class="pln"> </span><span class="typ">Graph</span><span class="pun">*</span><span class="pln"> graph </span><span class="pun">=</span><span class="pln"> malloc</span><span class="pun">(</span><span class="kwd">sizeof</span><span class="pun">(</span><span class="kwd">struct</span><span class="pln"> </span><span class="typ">Graph</span><span class="pun">));</span></li><li class="L9"><span class="pln">    graph</span><span class="pun">-&gt;</span><span class="pln">numVertices </span><span class="pun">=</span><span class="pln"> vertices</span><span class="pun">;</span></li><li class="L0"><span class="pln">&nbsp;</span></li><li class="L1"><span class="pln">    graph</span><span class="pun">-&gt;</span><span class="pln">adjLists </span><span class="pun">=</span><span class="pln"> malloc</span><span class="pun">(</span><span class="pln">vertices </span><span class="pun">*</span><span class="pln"> </span><span class="kwd">sizeof</span><span class="pun">(</span><span class="kwd">struct</span><span class="pln"> node</span><span class="pun">*));</span></li><li class="L2"><span class="pln">&nbsp;</span></li><li class="L3"><span class="pln">    graph</span><span class="pun">-&gt;</span><span class="pln">visited </span><span class="pun">=</span><span class="pln"> malloc</span><span class="pun">(</span><span class="pln">vertices </span><span class="pun">*</span><span class="pln"> </span><span class="kwd">sizeof</span><span class="pun">(</span><span class="typ">int</span><span class="pun">));</span></li><li class="L4"><span class="pln">&nbsp;</span></li><li class="L5"><span class="pln">    </span><span class="typ">int</span><span class="pln"> i</span><span class="pun">;</span></li><li class="L6"><span class="pln">    </span><span class="kwd">for</span><span class="pln"> </span><span class="pun">(</span><span class="pln">i </span><span class="pun">=</span><span class="pln"> </span><span class="lit">0</span><span class="pun">;</span><span class="pln"> i </span><span class="pun">&lt;</span><span class="pln"> vertices</span><span class="pun">;</span><span class="pln"> i</span><span class="pun">++)</span><span class="pln"> </span><span class="pun">{</span></li><li class="L7"><span class="pln">        graph</span><span class="pun">-&gt;</span><span class="pln">adjLists</span><span class="pun">[</span><span class="pln">i</span><span class="pun">]</span><span class="pln"> </span><span class="pun">=</span><span class="pln"> NULL</span><span class="pun">;</span></li><li class="L8"><span class="pln">        graph</span><span class="pun">-&gt;</span><span class="pln">visited</span><span class="pun">[</span><span class="pln">i</span><span class="pun">]</span><span class="pln"> </span><span class="pun">=</span><span class="pln"> </span><span class="lit">0</span><span class="pun">;</span></li><li class="L9"><span class="pln">    </span><span class="pun">}</span></li><li class="L0"><span class="pln">    </span><span class="kwd">return</span><span class="pln"> graph</span><span class="pun">;</span></li><li class="L1"><span class="pun">}</span></li><li class="L2"><span class="pln">&nbsp;</span></li><li class="L3"><span class="kwd">void</span><span class="pln"> addEdge</span><span class="pun">(</span><span class="kwd">struct</span><span class="pln"> </span><span class="typ">Graph</span><span class="pun">*</span><span class="pln"> graph</span><span class="pun">,</span><span class="pln"> </span><span class="typ">int</span><span class="pln"> src</span><span class="pun">,</span><span class="pln"> </span><span class="typ">int</span><span class="pln"> dest</span><span class="pun">)</span></li><li class="L4"><span class="pun">{</span></li><li class="L5"><span class="pln">    </span><span class="com">// Add edge from src to dest</span></li><li class="L6"><span class="pln">    </span><span class="kwd">struct</span><span class="pln"> node</span><span class="pun">*</span><span class="pln"> newNode </span><span class="pun">=</span><span class="pln"> createNode</span><span class="pun">(</span><span class="pln">dest</span><span class="pun">);</span></li><li class="L7"><span class="pln">    newNode</span><span class="pun">-&gt;</span><span class="pln">next </span><span class="pun">=</span><span class="pln"> graph</span><span class="pun">-&gt;</span><span class="pln">adjLists</span><span class="pun">[</span><span class="pln">src</span><span class="pun">];</span></li><li class="L8"><span class="pln">    graph</span><span class="pun">-&gt;</span><span class="pln">adjLists</span><span class="pun">[</span><span class="pln">src</span><span class="pun">]</span><span class="pln"> </span><span class="pun">=</span><span class="pln"> newNode</span><span class="pun">;</span></li><li class="L9"><span class="pln">&nbsp;</span></li><li class="L0"><span class="pln">    </span><span class="com">// Add edge from dest to src</span></li><li class="L1"><span class="pln">    newNode </span><span class="pun">=</span><span class="pln"> createNode</span><span class="pun">(</span><span class="pln">src</span><span class="pun">);</span></li><li class="L2"><span class="pln">    newNode</span><span class="pun">-&gt;</span><span class="pln">next </span><span class="pun">=</span><span class="pln"> graph</span><span class="pun">-&gt;</span><span class="pln">adjLists</span><span class="pun">[</span><span class="pln">dest</span><span class="pun">];</span></li><li class="L3"><span class="pln">    graph</span><span class="pun">-&gt;</span><span class="pln">adjLists</span><span class="pun">[</span><span class="pln">dest</span><span class="pun">]</span><span class="pln"> </span><span class="pun">=</span><span class="pln"> newNode</span><span class="pun">;</span></li><li class="L4"><span class="pun">}</span></li><li class="L5"><span class="pln">&nbsp;</span></li><li class="L6"><span class="kwd">void</span><span class="pln"> printGraph</span><span class="pun">(</span><span class="kwd">struct</span><span class="pln"> </span><span class="typ">Graph</span><span class="pun">*</span><span class="pln"> graph</span><span class="pun">)</span></li><li class="L7"><span class="pun">{</span></li><li class="L8"><span class="pln">    </span><span class="typ">int</span><span class="pln"> v</span><span class="pun">;</span></li><li class="L9"><span class="pln">    </span><span class="kwd">for</span><span class="pln"> </span><span class="pun">(</span><span class="pln">v </span><span class="pun">=</span><span class="pln"> </span><span class="lit">0</span><span class="pun">;</span><span class="pln"> v </span><span class="pun">&lt;</span><span class="pln"> graph</span><span class="pun">-&gt;</span><span class="pln">numVertices</span><span class="pun">;</span><span class="pln"> v</span><span class="pun">++)</span></li><li class="L0"><span class="pln">    </span><span class="pun">{</span></li><li class="L1"><span class="pln">        </span><span class="kwd">struct</span><span class="pln"> node</span><span class="pun">*</span><span class="pln"> temp </span><span class="pun">=</span><span class="pln"> graph</span><span class="pun">-&gt;</span><span class="pln">adjLists</span><span class="pun">[</span><span class="pln">v</span><span class="pun">];</span></li><li class="L2"><span class="pln">        printf</span><span class="pun">(</span><span class="str">"\n Adjacency list of vertex %d\n "</span><span class="pun">,</span><span class="pln"> v</span><span class="pun">);</span></li><li class="L3"><span class="pln">        </span><span class="kwd">while</span><span class="pln"> </span><span class="pun">(</span><span class="pln">temp</span><span class="pun">)</span></li><li class="L4"><span class="pln">        </span><span class="pun">{</span></li><li class="L5"><span class="pln">            printf</span><span class="pun">(</span><span class="str">"%d -&gt; "</span><span class="pun">,</span><span class="pln"> temp</span><span class="pun">-&gt;</span><span class="pln">vertex</span><span class="pun">);</span></li><li class="L6"><span class="pln">            temp </span><span class="pun">=</span><span class="pln"> temp</span><span class="pun">-&gt;</span><span class="pln">next</span><span class="pun">;</span></li><li class="L7"><span class="pln">        </span><span class="pun">}</span></li><li class="L8"><span class="pln">        printf</span><span class="pun">(</span><span class="str">"\n"</span><span class="pun">);</span></li><li class="L9"><span class="pln">    </span><span class="pun">}</span></li><li class="L0"><span class="pun">}</span></li></ol></pre></pre><h2><a class="anchor" id="header_Depth_First_Search_(DFS)_в_C++"></a>
  Depth First Search (DFS) в C++
 </h2><pre><pre class="lang-cpp prettyprint linenums prettyprinted" style=""><ol class="linenums"><li class="L0"><span class="com">#include</span><span class="pln"> </span><span class="str">&lt;iostream&gt;</span></li><li class="L1"><span class="com">#include</span><span class="pln"> </span><span class="str">&lt;list&gt;</span></li><li class="L2"><span class="kwd">using</span><span class="pln"> </span><span class="kwd">namespace</span><span class="pln"> std</span><span class="pun">;</span></li><li class="L3"><span class="pln">&nbsp;</span></li><li class="L4"><span class="kwd">class</span><span class="pln"> </span><span class="typ">Graph</span></li><li class="L5"><span class="pun">{</span></li><li class="L6"><span class="pln">    </span><span class="typ">int</span><span class="pln"> numVertices</span><span class="pun">;</span></li><li class="L7"><span class="pln">    </span><span class="typ">list</span><span class="pln"> </span><span class="pun">*</span><span class="pln">adjLists</span><span class="pun">;</span></li><li class="L8"><span class="pln">    </span><span class="kwd">bool</span><span class="pln"> </span><span class="pun">*</span><span class="pln">visited</span><span class="pun">;</span></li><li class="L9"><span class="pln">&nbsp;</span></li><li class="L0"><span class="kwd">public</span><span class="pun">:</span></li><li class="L1"><span class="pln">    </span><span class="typ">Graph</span><span class="pun">(</span><span class="typ">int</span><span class="pln"> V</span><span class="pun">);</span></li><li class="L2"><span class="pln">    </span><span class="kwd">void</span><span class="pln"> addEdge</span><span class="pun">(</span><span class="typ">int</span><span class="pln"> src</span><span class="pun">,</span><span class="pln"> </span><span class="typ">int</span><span class="pln"> dest</span><span class="pun">);</span></li><li class="L3"><span class="pln">    </span><span class="kwd">void</span><span class="pln"> DFS</span><span class="pun">(</span><span class="typ">int</span><span class="pln"> vertex</span><span class="pun">);</span></li><li class="L4"><span class="pun">};</span></li><li class="L5"><span class="pln">&nbsp;</span></li><li class="L6"><span class="typ">Graph</span><span class="pun">::</span><span class="typ">Graph</span><span class="pun">(</span><span class="typ">int</span><span class="pln"> vertices</span><span class="pun">)</span></li><li class="L7"><span class="pun">{</span></li><li class="L8"><span class="pln">    numVertices </span><span class="pun">=</span><span class="pln"> vertices</span><span class="pun">;</span></li><li class="L9"><span class="pln">    adjLists </span><span class="pun">=</span><span class="pln"> </span><span class="kwd">new</span><span class="pln"> </span><span class="typ">list</span><span class="pun">[</span><span class="pln">vertices</span><span class="pun">];</span></li><li class="L0"><span class="pln">    visited </span><span class="pun">=</span><span class="pln"> </span><span class="kwd">new</span><span class="pln"> </span><span class="kwd">bool</span><span class="pun">[</span><span class="pln">vertices</span><span class="pun">];</span></li><li class="L1"><span class="pun">}</span></li><li class="L2"><span class="pln">&nbsp;</span></li><li class="L3"><span class="kwd">void</span><span class="pln"> </span><span class="typ">Graph</span><span class="pun">::</span><span class="pln">addEdge</span><span class="pun">(</span><span class="typ">int</span><span class="pln"> src</span><span class="pun">,</span><span class="pln"> </span><span class="typ">int</span><span class="pln"> dest</span><span class="pun">)</span></li><li class="L4"><span class="pun">{</span></li><li class="L5"><span class="pln">    adjLists</span><span class="pun">[</span><span class="pln">src</span><span class="pun">].</span><span class="pln">push_front</span><span class="pun">(</span><span class="pln">dest</span><span class="pun">);</span></li><li class="L6"><span class="pun">}</span></li><li class="L7"><span class="pln">&nbsp;</span></li><li class="L8"><span class="kwd">void</span><span class="pln"> </span><span class="typ">Graph</span><span class="pun">::</span><span class="pln">DFS</span><span class="pun">(</span><span class="typ">int</span><span class="pln"> vertex</span><span class="pun">)</span></li><li class="L9"><span class="pun">{</span></li><li class="L0"><span class="pln">&nbsp;</span></li><li class="L1"><span class="pln">    visited</span><span class="pun">[</span><span class="pln">vertex</span><span class="pun">]</span><span class="pln"> </span><span class="pun">=</span><span class="pln"> </span><span class="kwd">true</span><span class="pun">;</span></li><li class="L2"><span class="pln">    </span><span class="typ">list</span><span class="pln"> adjList </span><span class="pun">=</span><span class="pln"> adjLists</span><span class="pun">[</span><span class="pln">vertex</span><span class="pun">];</span></li><li class="L3"><span class="pln">&nbsp;</span></li><li class="L4"><span class="pln">    cout </span><span class="pun">&lt;&lt;</span><span class="pln"> vertex </span><span class="pun">&lt;&lt;</span><span class="pln"> </span><span class="str">" "</span><span class="pun">;</span></li><li class="L5"><span class="pln">&nbsp;</span></li><li class="L6"><span class="pln">    </span><span class="typ">list</span><span class="pun">::</span><span class="typ">iterator</span><span class="pln"> i</span><span class="pun">;</span></li><li class="L7"><span class="pln">    </span><span class="kwd">for</span><span class="pun">(</span><span class="pln">i </span><span class="pun">=</span><span class="pln"> adjList</span><span class="pun">.</span><span class="pln">begin</span><span class="pun">();</span><span class="pln"> i </span><span class="pun">!=</span><span class="pln"> adjList</span><span class="pun">.</span><span class="pln">end</span><span class="pun">();</span><span class="pln"> </span><span class="pun">++</span><span class="pln">i</span><span class="pun">)</span></li><li class="L8"><span class="pln">        </span><span class="kwd">if</span><span class="pun">(!</span><span class="pln">visited</span><span class="pun">[*</span><span class="pln">i</span><span class="pun">])</span></li><li class="L9"><span class="pln">            DFS</span><span class="pun">(*</span><span class="pln">i</span><span class="pun">);</span></li><li class="L0"><span class="pun">}</span></li><li class="L1"><span class="pln">&nbsp;</span></li><li class="L2"><span class="typ">int</span><span class="pln"> main</span><span class="pun">()</span></li><li class="L3"><span class="pun">{</span></li><li class="L4"><span class="pln">    </span><span class="typ">Graph</span><span class="pln"> g</span><span class="pun">(</span><span class="lit">4</span><span class="pun">);</span></li><li class="L5"><span class="pln">    g</span><span class="pun">.</span><span class="pln">addEdge</span><span class="pun">(</span><span class="lit">0</span><span class="pun">,</span><span class="pln"> </span><span class="lit">1</span><span class="pun">);</span></li><li class="L6"><span class="pln">    g</span><span class="pun">.</span><span class="pln">addEdge</span><span class="pun">(</span><span class="lit">0</span><span class="pun">,</span><span class="pln"> </span><span class="lit">2</span><span class="pun">);</span></li><li class="L7"><span class="pln">    g</span><span class="pun">.</span><span class="pln">addEdge</span><span class="pun">(</span><span class="lit">1</span><span class="pun">,</span><span class="pln"> </span><span class="lit">2</span><span class="pun">);</span></li><li class="L8"><span class="pln">    g</span><span class="pun">.</span><span class="pln">addEdge</span><span class="pun">(</span><span class="lit">2</span><span class="pun">,</span><span class="pln"> </span><span class="lit">3</span><span class="pun">);</span></li><li class="L9"><span class="pln">&nbsp;</span></li><li class="L0"><span class="pln">    g</span><span class="pun">.</span><span class="pln">DFS</span><span class="pun">(</span><span class="lit">2</span><span class="pun">);</span></li><li class="L1"><span class="pln">&nbsp;</span></li><li class="L2"><span class="pln">    </span><span class="kwd">return</span><span class="pln"> </span><span class="lit">0</span><span class="pun">;</span></li><li class="L3"><span class="pun">}</span></li></ol></pre></pre><h2><a class="anchor" id="header_DFS_Java_код_(Java_code)"></a>
  DFS Java код (Java code)
 </h2><pre><pre class="lang-cpp prettyprint linenums prettyprinted" style=""><ol class="linenums"><li class="L0"><span class="kwd">import</span><span class="pln"> java</span><span class="pun">.</span><span class="pln">io</span><span class="pun">.*;</span></li><li class="L1"><span class="kwd">import</span><span class="pln"> java</span><span class="pun">.</span><span class="pln">util</span><span class="pun">.*;</span></li><li class="L2"><span class="pln">&nbsp;</span></li><li class="L3"><span class="pln">&nbsp;</span></li><li class="L4"><span class="kwd">class</span><span class="pln"> </span><span class="typ">Graph</span></li><li class="L5"><span class="pun">{</span></li><li class="L6"><span class="pln">    </span><span class="kwd">private</span><span class="pln"> </span><span class="typ">int</span><span class="pln"> numVertices</span><span class="pun">;</span></li><li class="L7"><span class="pln">    </span><span class="kwd">private</span><span class="pln"> </span><span class="typ">LinkedList</span><span class="pun">&lt;</span><span class="typ">Integer</span><span class="pun">&gt;</span><span class="pln"> adjLists</span><span class="pun">[];</span></li><li class="L8"><span class="pln">    </span><span class="kwd">private</span><span class="pln"> boolean visited</span><span class="pun">[];</span></li><li class="L9"><span class="pln">&nbsp;</span></li><li class="L0"><span class="pln">    </span><span class="typ">Graph</span><span class="pun">(</span><span class="typ">int</span><span class="pln"> vertices</span><span class="pun">)</span></li><li class="L1"><span class="pln">    </span><span class="pun">{</span></li><li class="L2"><span class="pln">        numVertices </span><span class="pun">=</span><span class="pln"> vertices</span><span class="pun">;</span></li><li class="L3"><span class="pln">        adjLists </span><span class="pun">=</span><span class="pln"> </span><span class="kwd">new</span><span class="pln"> </span><span class="typ">LinkedList</span><span class="pun">[</span><span class="pln">vertices</span><span class="pun">];</span></li><li class="L4"><span class="pln">        visited </span><span class="pun">=</span><span class="pln"> </span><span class="kwd">new</span><span class="pln"> boolean</span><span class="pun">[</span><span class="pln">vertices</span><span class="pun">];</span></li><li class="L5"><span class="pln">&nbsp;</span></li><li class="L6"><span class="pln">        </span><span class="kwd">for</span><span class="pln"> </span><span class="pun">(</span><span class="typ">int</span><span class="pln"> i </span><span class="pun">=</span><span class="pln"> </span><span class="lit">0</span><span class="pun">;</span><span class="pln"> i </span><span class="pun">&lt;</span><span class="pln"> vertices</span><span class="pun">;</span><span class="pln"> i</span><span class="pun">++)</span></li><li class="L7"><span class="pln">            adjLists</span><span class="pun">[</span><span class="pln">i</span><span class="pun">]</span><span class="pln"> </span><span class="pun">=</span><span class="pln"> </span><span class="kwd">new</span><span class="pln"> </span><span class="typ">LinkedList</span><span class="pun">&lt;</span><span class="typ">Integer</span><span class="pun">&gt;();</span></li><li class="L8"><span class="pln">    </span><span class="pun">}</span></li><li class="L9"><span class="pln">&nbsp;</span></li><li class="L0"><span class="pln">    </span><span class="kwd">void</span><span class="pln"> addEdge</span><span class="pun">(</span><span class="typ">int</span><span class="pln"> src</span><span class="pun">,</span><span class="pln"> </span><span class="typ">int</span><span class="pln"> dest</span><span class="pun">)</span></li><li class="L1"><span class="pln">    </span><span class="pun">{</span></li><li class="L2"><span class="pln">        adjLists</span><span class="pun">[</span><span class="pln">src</span><span class="pun">].</span><span class="pln">add</span><span class="pun">(</span><span class="pln">dest</span><span class="pun">);</span></li><li class="L3"><span class="pln">    </span><span class="pun">}</span></li><li class="L4"><span class="pln">&nbsp;</span></li><li class="L5"><span class="pln">    </span><span class="kwd">void</span><span class="pln"> DFS</span><span class="pun">(</span><span class="typ">int</span><span class="pln"> vertex</span><span class="pun">)</span></li><li class="L6"><span class="pln">    </span><span class="pun">{</span></li><li class="L7"><span class="pln">        visited</span><span class="pun">[</span><span class="pln">vertex</span><span class="pun">]</span><span class="pln"> </span><span class="pun">=</span><span class="pln"> </span><span class="kwd">true</span><span class="pun">;</span></li><li class="L8"><span class="pln">        </span><span class="typ">System</span><span class="pun">.</span><span class="pln">out</span><span class="pun">.</span><span class="pln">print</span><span class="pun">(</span><span class="pln">vertex </span><span class="pun">+</span><span class="pln"> </span><span class="str">" "</span><span class="pun">);</span></li><li class="L9"><span class="pln">&nbsp;</span></li><li class="L0"><span class="pln">        </span><span class="typ">Iterator</span><span class="pln"> ite </span><span class="pun">=</span><span class="pln"> adjLists</span><span class="pun">[</span><span class="pln">vertex</span><span class="pun">].</span><span class="pln">listIterator</span><span class="pun">();</span></li><li class="L1"><span class="pln">        </span><span class="kwd">while</span><span class="pln"> </span><span class="pun">(</span><span class="pln">ite</span><span class="pun">.</span><span class="pln">hasNext</span><span class="pun">())</span></li><li class="L2"><span class="pln">        </span><span class="pun">{</span></li><li class="L3"><span class="pln">            </span><span class="typ">int</span><span class="pln"> adj </span><span class="pun">=</span><span class="pln"> ite</span><span class="pun">.</span><span class="pln">next</span><span class="pun">();</span></li><li class="L4"><span class="pln">            </span><span class="kwd">if</span><span class="pln"> </span><span class="pun">(!</span><span class="pln">visited</span><span class="pun">[</span><span class="pln">adj</span><span class="pun">])</span></li><li class="L5"><span class="pln">                DFS</span><span class="pun">(</span><span class="pln">adj</span><span class="pun">);</span></li><li class="L6"><span class="pln">        </span><span class="pun">}</span></li><li class="L7"><span class="pln">    </span><span class="pun">}</span></li><li class="L8"><span class="pln">&nbsp;</span></li><li class="L9"><span class="pln">&nbsp;</span></li><li class="L0"><span class="pln">    </span><span class="kwd">public</span><span class="pln"> </span><span class="kwd">static</span><span class="pln"> </span><span class="kwd">void</span><span class="pln"> main</span><span class="pun">(</span><span class="typ">String</span><span class="pln"> args</span><span class="pun">[])</span></li><li class="L1"><span class="pln">    </span><span class="pun">{</span></li><li class="L2"><span class="pln">        </span><span class="typ">Graph</span><span class="pln"> g </span><span class="pun">=</span><span class="pln"> </span><span class="kwd">new</span><span class="pln"> </span><span class="typ">Graph</span><span class="pun">(</span><span class="lit">4</span><span class="pun">);</span></li><li class="L3"><span class="pln">&nbsp;</span></li><li class="L4"><span class="pln">         g</span><span class="pun">.</span><span class="pln">addEdge</span><span class="pun">(</span><span class="lit">0</span><span class="pun">,</span><span class="pln"> </span><span class="lit">1</span><span class="pun">);</span></li><li class="L5"><span class="pln">         g</span><span class="pun">.</span><span class="pln">addEdge</span><span class="pun">(</span><span class="lit">0</span><span class="pun">,</span><span class="pln"> </span><span class="lit">2</span><span class="pun">);</span></li><li class="L6"><span class="pln">         g</span><span class="pun">.</span><span class="pln">addEdge</span><span class="pun">(</span><span class="lit">1</span><span class="pun">,</span><span class="pln"> </span><span class="lit">2</span><span class="pun">);</span></li><li class="L7"><span class="pln">         g</span><span class="pun">.</span><span class="pln">addEdge</span><span class="pun">(</span><span class="lit">2</span><span class="pun">,</span><span class="pln"> </span><span class="lit">3</span><span class="pun">);</span></li><li class="L8"><span class="pln">&nbsp;</span></li><li class="L9"><span class="pln">        </span><span class="typ">System</span><span class="pun">.</span><span class="pln">out</span><span class="pun">.</span><span class="pln">println</span><span class="pun">(</span><span class="str">"Following is Depth First Traversal"</span><span class="pun">);</span></li><li class="L0"><span class="pln">&nbsp;</span></li><li class="L1"><span class="pln">        g</span><span class="pun">.</span><span class="pln">DFS</span><span class="pun">(</span><span class="lit">2</span><span class="pun">);</span></li><li class="L2"><span class="pln">    </span><span class="pun">}</span></li><li class="L3"><span class="pun">}</span></li></ol></pre></pre><h2><a class="anchor" id="header_DFS_в_Python"></a>
  DFS в Python
 </h2><pre><pre class="lang-cpp prettyprint linenums prettyprinted" style=""><ol class="linenums"><li class="L0"><span class="pln">def dfs</span><span class="pun">(</span><span class="pln">graph</span><span class="pun">,</span><span class="pln"> start</span><span class="pun">,</span><span class="pln"> visited</span><span class="pun">=</span><span class="typ">None</span><span class="pun">):</span></li><li class="L1"><span class="pln">    </span><span class="kwd">if</span><span class="pln"> visited is </span><span class="typ">None</span><span class="pun">:</span></li><li class="L2"><span class="pln">        visited </span><span class="pun">=</span><span class="pln"> </span><span class="typ">set</span><span class="pun">()</span></li><li class="L3"><span class="pln">    visited</span><span class="pun">.</span><span class="pln">add</span><span class="pun">(</span><span class="pln">start</span><span class="pun">)</span></li><li class="L4"><span class="pln">    print</span><span class="pun">(</span><span class="pln">start</span><span class="pun">)</span></li><li class="L5"><span class="pln">    </span><span class="kwd">for</span><span class="pln"> next in graph</span><span class="pun">[</span><span class="pln">start</span><span class="pun">]</span><span class="pln"> </span><span class="pun">-</span><span class="pln"> visited</span><span class="pun">:</span></li><li class="L6"><span class="pln">        dfs</span><span class="pun">(</span><span class="pln">graph</span><span class="pun">,</span><span class="pln"> next</span><span class="pun">,</span><span class="pln"> visited</span><span class="pun">)</span></li><li class="L7"><span class="pln">    </span><span class="kwd">return</span><span class="pln"> visited</span></li><li class="L8"><span class="pln">&nbsp;</span></li><li class="L9"><span class="pln">graph </span><span class="pun">=</span><span class="pln"> </span><span class="pun">{</span><span class="str">'0'</span><span class="pun">:</span><span class="pln"> </span><span class="typ">set</span><span class="pun">([</span><span class="str">'1'</span><span class="pun">,</span><span class="pln"> </span><span class="str">'2'</span><span class="pun">]),</span></li><li class="L0"><span class="pln">         </span><span class="str">'1'</span><span class="pun">:</span><span class="pln"> </span><span class="typ">set</span><span class="pun">([</span><span class="str">'0'</span><span class="pun">,</span><span class="pln"> </span><span class="str">'3'</span><span class="pun">,</span><span class="pln"> </span><span class="str">'4'</span><span class="pun">]),</span></li><li class="L1"><span class="pln">         </span><span class="str">'2'</span><span class="pun">:</span><span class="pln"> </span><span class="typ">set</span><span class="pun">([</span><span class="str">'0'</span><span class="pun">]),</span></li><li class="L2"><span class="pln">         </span><span class="str">'3'</span><span class="pun">:</span><span class="pln"> </span><span class="typ">set</span><span class="pun">([</span><span class="str">'1'</span><span class="pun">]),</span></li><li class="L3"><span class="pln">         </span><span class="str">'4'</span><span class="pun">:</span><span class="pln"> </span><span class="typ">set</span><span class="pun">([</span><span class="str">'2'</span><span class="pun">,</span><span class="pln"> </span><span class="str">'3'</span><span class="pun">])}</span></li><li class="L4"><span class="pln">&nbsp;</span></li><li class="L5"><span class="pln">dfs</span><span class="pun">(</span><span class="pln">graph</span><span class="pun">,</span><span class="pln"> </span><span class="str">'0'</span><span class="pun">)</span></li></ol></pre></pre></div><a href="https://timeweb.com/ru/?i=27415" rel="nofollow" target="_blank"><div class="media pt-3"><img class="mr-3" src="./Алгоритм DFS («Depth-first search» или «Поиск в глубину»)_files/timeweb-120-90.jpg" alt="Рекомендуем хостинг TIMEWEB"><div class="media-body"><h5 class="mt-0">Рекомендуем хостинг TIMEWEB</h5>
            Стабильный хостинг, на котором располагается социальная сеть EVILEG. Для проектов на Django рекомендуем VDS хостинг.
        </div></div></a></div><div class="card-footer border-top py-3 px-4"><p><strong>Рекомендуемые статьи по этой тематике</strong></p><ul><li><a href="https://evileg.com/ru/post/524/">Алгоритм Прима</a></li><li><a href="https://evileg.com/ru/post/523/">Алгоритм Краскала</a></li><li><a href="https://evileg.com/ru/post/512/">Поиск в ширину (Breadth first search, BFS)</a></li><li><a href="https://evileg.com/ru/post/511/">Матрица смежности</a></li><li><a href="https://evileg.com/ru/post/492/">Граф. Структура данных.</a></li><li><a href="https://evileg.com/ru/post/491/">Двоичное дерево поиска (Binary Search Tree (BST))</a></li><li><a href="https://evileg.com/ru/post/490/">Обход дерева – центрированный (inorder), прямой (preorder) и обратный (postorder) (три основных способа обхода)</a></li><li><a href="https://evileg.com/ru/post/467/">Стек</a></li></ul><p><strong class="mr-1">По статье задано</strong><a href="https://evileg.com/ru/forum/?search=article:494">0<span class="ml-1">вопрос(ов)</span></a></p><p><strong class="mr-1">Источник: </strong><a href="https://www.programiz.com/dsa/graph-dfs" rel="nofollow" target="_blank">Programiz</a></p><h4><a href="https://evileg.com/ru/post/494/subscribers/">Подписчики</a></h4><div class="switch"><label onclick="Global.nonlogin()" title="Только зарегистрированные пользователи могут подписываться на обновления" class="text-dark"><input type="checkbox" disabled=""><span class="bmd-switch-track"></span>Подписка на обсуждение<span class="badge badge-light ml-2">2</span></label></div><ul class="list-inline mb-0"><li class="list-inline-item"><a class="btn btn-sm btn-dark" href="https://evileg.com/ru/knowledge/algorithms/" title="Перейти к объекту подписки"><span class="mdi mdi-share mdi-18px mdi-0"></span></a></li><li class="list-inline-item"><div class="switch"><label onclick="Global.nonlogin()" title="Только зарегистрированные пользователи могут подписываться на обновления" class="text-dark"><input type="checkbox" disabled=""><span class="bmd-switch-track"></span>Подписка на раздел<span class="badge badge-light ml-2">64</span></label></div></li></ul></div><div class="border-top px-3">
            Поддержать автора
            
            
    
    <a class="btn btn-outline-primary m-2" href="https://evileg.com/ru/post/494/#" data-toggle="modal" data-target="#donateDialog"><small>Donate</small></a><div class="modal fade" id="donateDialog" tabindex="-1" role="dialog" aria-labelledby="donateDialogLabel" aria-hidden="true"><div class="modal-dialog" role="document"><div class="modal-content"><div class="modal-header"><h5 class="modal-title" id="donateDialogLabel">Платёжная система</h5><button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button></div><div class="modal-body"><ul class="list-unstyled"><li><a href="https://money.yandex.ru/to/410018355146875" target="_blank" rel="nofollow">Яндекс.Деньги</a></li></ul></div><div class="modal-footer"><button type="button" class="btn btn-secondary" data-dismiss="modal">Закрыть</button></div></div></div></div></div><ul class="card-footer act-footer"><li class="act-btn" title="Просмотры"><span class="mdi mdi-eye">66790</span></li><li title="Комментарии"><a class="act-btn mdi mdi-comment" href="https://evileg.com/ru/post/494/#comments">0</a></li><li class="act-btn" onclick="Global.nonlogin()" title="Только зарегистрированные пользователи могут добавлять в избранное"><span data-icon="favorite" class="mdi mdi-star"></span><span data-count="favorite">1</span></li><li class="act-btn" onclick="Global.nonlogin()" title="Только зарегистрированные пользователи могут оценивать"><span data-icon="like" class="mdi mdi-thumb-up"></span><span data-count="like">2</span></li><li class="act-btn" onclick="Global.nonlogin()" title="Только зарегистрированные пользователи могут оценивать"><span data-icon="dislike" class="mdi mdi-thumb-down"></span><span data-count="dislike">0</span></li><li class="act-btn" onclick="Global.nonlogin()" title="Поделилось с друзьями"><span class="mdi mdi-bullhorn"></span><span></span></li><li class="float-right"><button class="act-btn" onclick="$(&#39;body&#39;).share_social(&#39;https://evileg.com/ru/post/494/&#39;)" title="Поделиться ссылкой"><span class="mdi mdi-share-variant mdi-0"></span></button></li></ul></div></article><a class="anchor" id="comments"></a><div id="comments-feed"></div><div class="card card-warning m-3 box-shadow"><div class="card-header bg-warning"><h3 class="card-title mb-0">Комментарии</h3></div><div class="card-body">
            
            
            Только авторизованные пользователи могут публиковать комментарии.<br>Пожалуйста, <a href="https://evileg.com/ru/accounts/login/">авторизуйтесь</a> или <a href="https://evileg.com/ru/accounts/register/">зарегистрируйтесь</a></div></div></div></div><div class="col-12 col-lg-3 p-0 pb-3 bg-light " style="height: auto !important; min-height: 0px !important;"><div class="card box-shadow m-2"><script async="" src="./Алгоритм DFS («Depth-first search» или «Поиск в глубину»)_files/f(4).txt"></script><!-- Evileg COM Header --><ins class="adsbygoogle" style="display: block; height: 600px;" data-ad-client="ca-pub-8877856398367795" data-ad-slot="4753134862" data-ad-format="auto" data-full-width-responsive="true" data-adsbygoogle-status="done" data-ad-status="unfilled"><ins id="aswift_1_expand" style="border: none; height: 600px; width: 262px; margin: 0px; padding: 0px; position: relative; visibility: visible; background-color: transparent; display: inline-table;" tabindex="0" title="Advertisement" aria-label="Advertisement"><ins id="aswift_1_anchor" style="border: none; height: 600px; width: 262px; margin: 0px; padding: 0px; position: relative; visibility: visible; background-color: transparent; display: block; overflow: visible;"><iframe id="aswift_1" name="aswift_1" style="left:0;position:absolute;top:0;border:0;width:262px;height:600px" sandbox="allow-forms allow-popups allow-popups-to-escape-sandbox allow-same-origin allow-scripts allow-top-navigation-by-user-activation" width="262" height="600" frameborder="0" marginwidth="0" marginheight="0" vspace="0" hspace="0" allowtransparency="true" scrolling="no" src="./Алгоритм DFS («Depth-first search» или «Поиск в глубину»)_files/ads(1).html" data-google-container-id="a!2" data-google-query-id="CJmpm4r0-fYCFRSTmgodXV8G9w" data-load-complete="true"></iframe></ins></ins></ins><script>
     (adsbygoogle = window.adsbygoogle || []).push({});
</script></div><div class="sticky" style="height: auto !important;"><div class="card box-shadow m-2"><h5 class="card-header text-center">Timeweb</h5><div class="card-body"><p>Позвольте мне порекомендовать вам отличный хостинг, на котором расположен EVILEG.</p><p>В течение многих лет Timeweb доказывает свою стабильность.</p><p>Для проектов на Django рекомендую VDS хостинг</p><a class="btn btn-outline-primary btn-block" href="https://timeweb.com/ru/?i=27415&amp;utm_source=evileg&amp;utm_medium=sidebar&amp;utm_campaign=ru" target="_blank" rel="nofollow">Посмотреть Хостинг</a></div></div><div class="card box-shadow m-2"><script async="" src="./Алгоритм DFS («Depth-first search» или «Поиск в глубину»)_files/f(4).txt"></script><!-- Evileg COM Sidebar --><ins class="adsbygoogle" style="display: block; height: 0px;" data-ad-client="ca-pub-8877856398367795" data-ad-slot="7952216063" data-ad-format="auto" data-full-width-responsive="true" data-adsbygoogle-status="done" data-ad-status="unfilled"><ins id="aswift_2_expand" style="border: none; height: 0px; width: 262px; margin: 0px; padding: 0px; position: relative; visibility: visible; background-color: transparent; display: inline-table;" tabindex="0" title="Advertisement" aria-label="Advertisement"><ins id="aswift_2_anchor" style="border: none; height: 0px; width: 262px; margin: 0px; padding: 0px; position: relative; visibility: visible; background-color: transparent; display: block; overflow: hidden; opacity: 0;"><iframe id="aswift_2" name="aswift_2" style="left: 0px; position: absolute; top: 0px; border: 0px; width: 262px; height: 0px;" sandbox="allow-forms allow-popups allow-popups-to-escape-sandbox allow-same-origin allow-scripts allow-top-navigation-by-user-activation" width="262" height="0" frameborder="0" marginwidth="0" marginheight="0" vspace="0" hspace="0" allowtransparency="true" scrolling="no" src="./Алгоритм DFS («Depth-first search» или «Поиск в глубину»)_files/ads(2).html" data-google-container-id="a!3" data-google-query-id="CPLspIr0-fYCFRnrmgodvboBMw" data-load-complete="true"></iframe></ins></ins></ins><script>
     (adsbygoogle = window.adsbygoogle || []).push({});
</script></div><div id="toTop" class="text-center mt-3 pt-3" style=""><button onclick="toTop()" class="btn btn-primary active">Наверх</button></div></div></div></main><div class="container-fluid bg-light"><div class="row"><div class="col-12 col-lg-9 px-0"><div class="card border-top box-shadow m-2"><div class="card-header"><div class="row"><a class="col-md-4" href="https://evileg.com/ru/tests/pt/recent/"><strong>Последние пройденные тесты</strong></a><a class="col-md-4" href="https://evileg.com/ru/tests/pt/rating/"><strong>Рейтинг</strong></a></div></div><div class="card-body"><div class="row"><div class="media col-md-4"><a class="mr-3 text-decoration-none" href="https://evileg.com/ru/users/Scandal1996/"><div class="m-0 p-0 position-relative"><div class="avatar-3 rounded-circle m-0 text-center aqua-gradient box-shadow"><div class="text-center align-middle w-100 h-100 avatar-initials text-uppercase avatar-initials-size-3">S</div></div></div></a><div class="media-body"><ul class="list-inline mb-1"><li class="list-inline-item"><a href="https://evileg.com/ru/users/Scandal1996/"><strong>Scandal1996</strong></a></li><li class="list-inline-item text-muted mr-2"><small>1 апреля 2022 г. 23:56</small></li></ul><p class="mb-1"><a href="https://evileg.com/ru/tests/t/8/">C++ - Тест 006. Перечисления</a></p><ul class="list-inline mb-0"><li class="list-inline-item"><strong>Результат:</strong><span class="badge badge-light mx-1">50</span>баллов,</li><li class="list-inline-item">Очки рейтинга<span class="badge badge-light mx-1">-4</span></li><li class="list-inline-item"><span class="mdi mdi-close-outline text-danger mdi-0" title="Тест не сдан"></span></li></ul></div></div><div class="media col-md-4"><a class="mr-3 text-decoration-none" href="https://evileg.com/ru/users/Scandal1996/"><div class="m-0 p-0 position-relative"><div class="avatar-3 rounded-circle m-0 text-center aqua-gradient box-shadow"><div class="text-center align-middle w-100 h-100 avatar-initials text-uppercase avatar-initials-size-3">S</div></div></div></a><div class="media-body"><ul class="list-inline mb-1"><li class="list-inline-item"><a href="https://evileg.com/ru/users/Scandal1996/"><strong>Scandal1996</strong></a></li><li class="list-inline-item text-muted mr-2"><small>1 апреля 2022 г. 23:52</small></li></ul><p class="mb-1"><a href="https://evileg.com/ru/tests/t/6/">C++ - Тест 004. Указатели, Массивы и Циклы</a></p><ul class="list-inline mb-0"><li class="list-inline-item"><strong>Результат:</strong><span class="badge badge-light mx-1">40</span>баллов,</li><li class="list-inline-item">Очки рейтинга<span class="badge badge-light mx-1">-8</span></li><li class="list-inline-item"><span class="mdi mdi-close-outline text-danger mdi-0" title="Тест не сдан"></span></li></ul></div></div><div class="media col-md-4"><a class="mr-3 text-decoration-none" href="https://evileg.com/ru/users/Scandal1996/"><div class="m-0 p-0 position-relative"><div class="avatar-3 rounded-circle m-0 text-center aqua-gradient box-shadow"><div class="text-center align-middle w-100 h-100 avatar-initials text-uppercase avatar-initials-size-3">S</div></div></div></a><div class="media-body"><ul class="list-inline mb-1"><li class="list-inline-item"><a href="https://evileg.com/ru/users/Scandal1996/"><strong>Scandal1996</strong></a></li><li class="list-inline-item text-muted mr-2"><small>1 апреля 2022 г. 23:48</small></li></ul><p class="mb-1"><a href="https://evileg.com/ru/tests/t/1/">C++ - Тест 001. Первая программа и типы данных</a></p><ul class="list-inline mb-0"><li class="list-inline-item"><strong>Результат:</strong><span class="badge badge-light mx-1">93</span>баллов,</li><li class="list-inline-item">Очки рейтинга<span class="badge badge-light mx-1">8</span></li><li class="list-inline-item"><span class="mdi mdi-check-outline text-success mdi-0" title="Тест сдан"></span></li></ul></div></div></div></div></div><div class="card box-shadow m-2"><div class="card-header"><strong>Популярные публикации за последние 90 дней</strong></div><div class="card-body"><div class="py-1"><span class="badge badge-secondary float-right mdi mdi-eye">3.1K</span><a href="https://evileg.com/ru/post/658/">Django Rest Framework - Урок 001.  Добавление аутентификации по токену</a></div><div class="py-1"><span class="badge badge-secondary float-right mdi mdi-eye">1.2K</span><a href="https://evileg.com/ru/post/655/">Django - Урок 055.  Как написать функционал auto populate field</a></div><div class="py-1"><span class="badge badge-secondary float-right mdi mdi-eye">1.2K</span><a href="https://evileg.com/ru/post/656/">Django - Урок 056. Как конвертировать изображение в формат WEBP при сохранении в ImageField</a></div><div class="py-1"><span class="badge badge-secondary float-right mdi mdi-eye">1.1K</span><a href="https://evileg.com/ru/post/654/">Qt/C++ Урок 092. Создание переводов для внешних источников текста</a></div><div class="py-1"><span class="badge badge-secondary float-right mdi mdi-eye">795</span><a href="https://evileg.com/ru/post/657/">Django - Урок 057. Поддержка мультиязычности в MarkdownField с функционалом auto populate</a></div></div></div><div class="card box-shadow m-2"><div class="card-header"><strong>Последние комментарии</strong></div><div class="card-body"><div class="py-2"><div class="media"><a class="mr-3 text-decoration-none" href="https://evileg.com/ru/users/skynetpro.ru/"><div class="m-0 p-0 position-relative"><div class="bg-white avatar-3 rounded-circle m-0 box-shadow"><img loading="lazy" class="avatar-3 rounded-circle m-0" src="./Алгоритм DFS («Depth-first search» или «Поиск в глубину»)_files/avatar_iu7MhlX.jpg"></div></div></a><div class="media-body"><ul class="list-inline mb-1"><li class="list-inline-item"><a href="https://evileg.com/ru/users/skynetpro.ru/"><strong>NSProject</strong></a></li><li class="list-inline-item text-muted mr-2"><small>3 апреля 2022 г. 1:06</small></li></ul><p class="mb-1"><a href="https://evileg.com/ru/post/246/#comment-2372">Django - Урок 023. Like Dislike система с помощью GenericForeignKey</a></p><div>   Меня интересует только один вопрос в плате SQL запросов. Их почему то плодится очень много с системой лайков и дизлайков </div></div><script type="application/ld+json">{"@context": "http://schema.org", "@type": "Comment", "author": "NSProject", "url": "/ru/post/246/#comment-2372", "name": "Django - Урок 023. Like Dislike система с помощью GenericForeignKey", "headline": "Django - Урок 023. Like Dislike система с помощью GenericForeignKey", "description": "\n \n  Меня интересует только один вопрос в плате SQL запросов. Их почему то плодится очень много с системой лайков и дизлайков\n \n", "datePublished": "2022-04-02T18:06:39.959208+00:00", "interactionStatistic": [{"@type": "InteractionCounter", "interactionType": "BookmarkAction", "userInteractionCount": 0}, {"@type": "InteractionCounter", "interactionType": "LikeAction", "userInteractionCount": 0}, {"@type": "InteractionCounter", "interactionType": "DislikeAction", "userInteractionCount": 0}]}</script></div></div><div class="py-2"><div class="media"><a class="mr-3 text-decoration-none" href="https://evileg.com/ru/users/skynetpro.ru/"><div class="m-0 p-0 position-relative"><div class="bg-white avatar-3 rounded-circle m-0 box-shadow"><img loading="lazy" class="avatar-3 rounded-circle m-0" src="./Алгоритм DFS («Depth-first search» или «Поиск в глубину»)_files/avatar_iu7MhlX.jpg"></div></div></a><div class="media-body"><ul class="list-inline mb-1"><li class="list-inline-item"><a href="https://evileg.com/ru/users/skynetpro.ru/"><strong>NSProject</strong></a></li><li class="list-inline-item text-muted mr-2"><small>3 апреля 2022 г. 1:03</small></li></ul><p class="mb-1"><a href="https://evileg.com/ru/post/546/#comment-2371">Django - Урок 048. Как добавить статус онлайн на сайте</a></p><div>   А вы создали в settings.py?  AUTH_USER_MODEL = 'you_app.User'   А так же во всех моделях где есть внешний ключ на юзера нужно ставить  settings.AUTH_USER_MODEL</div></div><script type="application/ld+json">{"@context": "http://schema.org", "@type": "Comment", "author": "NSProject", "url": "/ru/post/546/#comment-2371", "name": "Django - Урок 048. Как добавить статус онлайн на сайте", "headline": "Django - Урок 048. Как добавить статус онлайн на сайте", "description": "\n \n  А вы создали в settings.py?\n \n AUTH_USER_MODEL = 'you_app.User'\n\n \n  А так же во всех моделях где есть внешний ключ на юзера нужно ставить\n \n settings.AUTH_USER_MODEL\n\n", "datePublished": "2022-04-02T18:03:49.661899+00:00", "interactionStatistic": [{"@type": "InteractionCounter", "interactionType": "BookmarkAction", "userInteractionCount": 0}, {"@type": "InteractionCounter", "interactionType": "LikeAction", "userInteractionCount": 0}, {"@type": "InteractionCounter", "interactionType": "DislikeAction", "userInteractionCount": 0}]}</script></div></div><div class="py-2"><div class="media"><a class="mr-3 text-decoration-none" href="https://evileg.com/ru/users/Vitalii181190/"><div class="m-0 p-0 position-relative"><div class="avatar-3 rounded-circle m-0 text-center sage-percuasion-gradient box-shadow"><div class="text-center align-middle w-100 h-100 avatar-initials text-uppercase avatar-initials-size-3">V</div></div></div></a><div class="media-body"><ul class="list-inline mb-1"><li class="list-inline-item"><a href="https://evileg.com/ru/users/Vitalii181190/"><strong>Vitalii181190</strong></a></li><li class="list-inline-item text-muted mr-2"><small>3 апреля 2022 г. 0:09</small></li></ul><p class="mb-1"><a href="https://evileg.com/ru/post/546/#comment-2370">Django - Урок 048. Как добавить статус онлайн на сайте</a></p><div>   Сделал всё как описано но при создании миграций возникает ошибка:    SystemCheckError: System check identified some issues:    ERRORS:    auth.User.groups: (fields.E304) Reverse accessor …</div></div><script type="application/ld+json">{"@context": "http://schema.org", "@type": "Comment", "author": "Vitalii181190", "url": "/ru/post/546/#comment-2370", "name": "Django - Урок 048. Как добавить статус онлайн на сайте", "headline": "Django - Урок 048. Как добавить статус онлайн на сайте", "description": "\n \n  Сделал всё как описано но при создании миграций возникает ошибка:\n  \n  SystemCheckError: System check identified some issues:\n \n \n  ERRORS:\n  \n  auth.User.groups: (fields.E304) Reverse accessor for 'auth.User.groups' clashes with reverse accessor for 'users.User.groups'.\n  \n  HINT: Add or change a related_name argument to the definition for 'auth.User.groups' or 'users.User.groups'.\n  \n  auth.User.user_permissions: (fields.E304) Reverse accessor for 'auth.User.user_permissions' clashes with reverse accessor for 'users.User.user_permissions'.\n  \n  HINT: Add or change a related_name argument to the definition for 'auth.User.user_permissions' or 'users.User.user_permissions'.\n  \n  users.User.groups: (fields.E304) Reverse accessor for 'users.User.groups' clashes with reverse accessor for 'auth.User.groups'.\n  \n  HINT: Add or change a related_name argument to the definition for 'users.User.groups' or 'auth.User.groups'.\n  \n  users.User.user_permissions: (fields.E304) Reverse accessor for 'users.User.user_permissions' clashes with reverse accessor for 'auth.User.user_permissions'.\n  \n  HINT: Add or change a related_name argument to the definition for 'users.User.user_permissions' or 'auth.User.user_permissions'.\n \n", "datePublished": "2022-04-02T17:09:18.891171+00:00", "interactionStatistic": [{"@type": "InteractionCounter", "interactionType": "BookmarkAction", "userInteractionCount": 0}, {"@type": "InteractionCounter", "interactionType": "LikeAction", "userInteractionCount": 0}, {"@type": "InteractionCounter", "interactionType": "DislikeAction", "userInteractionCount": 0}]}</script></div></div><div class="py-2"><div class="media"><a class="mr-3 text-decoration-none" href="https://evileg.com/ru/users/bycbo/"><div class="m-0 p-0 position-relative"><div class="avatar-3 rounded-circle m-0 text-center aqua-gradient box-shadow"><div class="text-center align-middle w-100 h-100 avatar-initials text-uppercase avatar-initials-size-3">b</div></div></div></a><div class="media-body"><ul class="list-inline mb-1"><li class="list-inline-item"><a href="https://evileg.com/ru/users/bycbo/"><strong>bycbo</strong></a></li><li class="list-inline-item text-muted mr-2"><small>30 марта 2022 г. 3:16</small></li></ul><p class="mb-1"><a href="https://evileg.com/ru/post/77/#comment-2368">Qt/C++ - Урок 014. Динамическое создание виджетов в Qt</a></p><div>   а можно посмотреть финальный проект? Что-то не пойму что я делаю не так </div></div><script type="application/ld+json">{"@context": "http://schema.org", "@type": "Comment", "author": "bycbo", "url": "/ru/post/77/#comment-2368", "name": "Qt/C++ - Урок 014. Динамическое создание виджетов в Qt", "headline": "Qt/C++ - Урок 014. Динамическое создание виджетов в Qt", "description": "\n \n  а можно посмотреть финальный проект? Что-то не пойму что я делаю не так\n \n", "datePublished": "2022-03-29T20:16:56.309872+00:00", "interactionStatistic": [{"@type": "InteractionCounter", "interactionType": "BookmarkAction", "userInteractionCount": 0}, {"@type": "InteractionCounter", "interactionType": "LikeAction", "userInteractionCount": 0}, {"@type": "InteractionCounter", "interactionType": "DislikeAction", "userInteractionCount": 0}]}</script></div></div><div class="py-2"><div class="media"><a class="mr-3 text-decoration-none" href="https://evileg.com/ru/users/olegsemenchuk79/"><div class="m-0 p-0 position-relative"><div class="avatar-3 rounded-circle m-0 text-center dark-knight-gradient box-shadow"><div class="text-center align-middle w-100 h-100 avatar-initials text-uppercase avatar-initials-size-3">KR</div></div></div></a><div class="media-body"><ul class="list-inline mb-1"><li class="list-inline-item"><a href="https://evileg.com/ru/users/olegsemenchuk79/"><strong>Kot Roth</strong></a></li><li class="list-inline-item text-muted mr-2"><small>28 марта 2022 г. 18:14</small></li></ul><p class="mb-1"><a href="https://evileg.com/ru/post/642/#comment-2367">5 Способов убрать ненужные символы из строки на Python</a></p><div>   помогло, спасибо </div></div><script type="application/ld+json">{"@context": "http://schema.org", "@type": "Comment", "author": "Kot Roth", "url": "/ru/post/642/#comment-2367", "name": "5 Способов убрать ненужные символы из строки на Python", "headline": "5 Способов убрать ненужные символы из строки на Python", "description": "\n \n  помогло, спасибо\n \n", "datePublished": "2022-03-28T11:14:36.242922+00:00", "interactionStatistic": [{"@type": "InteractionCounter", "interactionType": "BookmarkAction", "userInteractionCount": 0}, {"@type": "InteractionCounter", "interactionType": "LikeAction", "userInteractionCount": 0}, {"@type": "InteractionCounter", "interactionType": "DislikeAction", "userInteractionCount": 0}]}</script></div></div></div></div><div class="card box-shadow m-2"><div class="card-header"><strong>Сейчас обсуждают на форуме</strong></div><div class="card-body"><div class="py-2"><div class="media"><a class="mr-3 text-decoration-none" href="https://evileg.com/ru/users/juvf/"><div class="m-0 p-0 position-relative"><div class="bg-white avatar-3 rounded-circle m-0 box-shadow"><img loading="lazy" class="avatar-3 rounded-circle m-0" src="./Алгоритм DFS («Depth-first search» или «Поиск в глубину»)_files/avatar(1).jpg"></div></div></a><div class="media-body"><ul class="list-inline mb-1"><li class="list-inline-item"><a href="https://evileg.com/ru/users/juvf/"><strong>juvf</strong></a></li><li class="list-inline-item text-muted mr-2"><small>1 апреля 2022 г. 18:12</small></li></ul><p class="mb-1"><a href="https://evileg.com/ru/forum/topic/1726/#post-9364">Виджет настройки</a></p><div>   ну про CoverFlow вобможно в будущем можно будет и визуализацию выпуклости (колеса) сделать, спсибо.    Сейчас пока нужен просто виджет настройки/регулировки.... Как это с помошью ScrollView р…</div></div><script type="application/ld+json">{"@context": "http://schema.org", "@type": "Answer", "author": "juvf", "url": "/ru/forum/topic/1726/#post-9364", "name": "Виджет настройки", "headline": "Виджет настройки", "description": "\n \n  ну про CoverFlow вобможно в будущем можно будет и визуализацию выпуклости (колеса) сделать, спсибо.\n \n \n  Сейчас пока нужен просто виджет настройки/регулировки.... Как это с помошью ScrollView реализовать? (рассмотрим горизонтальную ориентацию)\n  \n  Допустим я нарисую шкалу в png. ширина шкалы 500 пикселей. Сделаю ScrollView шириной 100 пикселей. Помещю в ScrollView картинку шкалы.\n  \n  Пальцем буду её двигать.... мне нужно как то зациклить. Протолкну шкалу по ScrollView до конца, а потом что?\n \n", "datePublished": "2022-04-01T11:12:52.568158+00:00", "interactionStatistic": [{"@type": "InteractionCounter", "interactionType": "BookmarkAction", "userInteractionCount": 0}, {"@type": "InteractionCounter", "interactionType": "LikeAction", "userInteractionCount": 0}, {"@type": "InteractionCounter", "interactionType": "DislikeAction", "userInteractionCount": 0}]}</script></div></div><div class="py-2"><div class="media"><a class="mr-3 text-decoration-none" href="https://evileg.com/ru/users/IscanderChe/"><div class="m-0 p-0 position-relative"><div class="bg-white avatar-3 rounded-circle m-0 box-shadow"><img loading="lazy" class="avatar-3 rounded-circle m-0" src="./Алгоритм DFS («Depth-first search» или «Поиск в глубину»)_files/avatar(2).jpg"></div></div></a><div class="media-body"><ul class="list-inline mb-1"><li class="list-inline-item"><a href="https://evileg.com/ru/users/IscanderChe/"><strong>IscanderChe</strong></a></li><li class="list-inline-item text-muted mr-2"><small>31 марта 2022 г. 1:06</small></li></ul><p class="mb-1"><a href="https://evileg.com/ru/forum/topic/1725/">Доступ по SSH по ключу</a></p><div>   Добрый день!    Подскажите, как настроить доступ по SSH по ключу, если сервер SSH крутится на Debian, а клиент - на Win 10?    Курение мануалов из сети, к сожалению, не помогло...    Де…</div></div><script type="application/ld+json">{"@context": "http://schema.org", "@type": "Question", "author": "IscanderChe", "url": "/ru/forum/topic/1725/", "name": "Доступ по SSH по ключу", "headline": "Доступ по SSH по ключу", "description": "\n \n  Добрый день!\n \n \n  Подскажите, как настроить доступ по SSH по ключу, если сервер SSH крутится на Debian, а клиент - на Win 10?\n \n \n  Курение мануалов из сети, к сожалению, не помогло...\n \n \n  Делал так.\n \n \n  На винде:\n  \n  ssh-keygen\n \n \n  На вопрос утилиты, куда сохранить, выбрал своё расположение. В папке %path_to_.ssh% появилось два файла: id_rsa.pub и id_rsa.\n \n \n  ssh-copy-id user@server\n \n \n  Ответ такой: \"'ssh-copy-id' is not recognized as an internal or external command, operable program or batch file.\"\n \n \n  Поэтому иду другим путём.\n \n \n  На линуксе через консоль винды:\n  \n  mkdir\n  \n   /.ssh\n   \n   chmod 0700\n  \n  /.ssh\n  \n  touch\n  \n   /.ssh/authorized_keys\n   \n   chmod 0644\n  \n  /.ssh/authorized_keys\n \n \n  Через консоль винды вставил ключ из id_rsa.pub и сохранил файл.\n  \n  Перезапустил сервис. Итог: всё равно требуется пароль. Настройка сервера \"PubkeyAuthentication yes\".\n \n \n  Через сервисы PuTTY заработало, но мне хотелось бы чисто через консоль винды.\n \n", "datePublished": "2022-03-30T18:06:32.170836+00:00", "interactionStatistic": [{"@type": "InteractionCounter", "interactionType": "BookmarkAction", "userInteractionCount": 0}, {"@type": "InteractionCounter", "interactionType": "LikeAction", "userInteractionCount": 0}, {"@type": "InteractionCounter", "interactionType": "DislikeAction", "userInteractionCount": 0}]}</script></div></div><div class="py-2"><div class="media"><a class="mr-3 text-decoration-none" href="https://evileg.com/ru/users/mihail.dark/"><div class="m-0 p-0 position-relative"><div class="bg-white avatar-3 rounded-circle m-0 box-shadow"><img loading="lazy" class="avatar-3 rounded-circle m-0" src="./Алгоритм DFS («Depth-first search» или «Поиск в глубину»)_files/avatar(3).jpg"></div></div></a><div class="media-body"><ul class="list-inline mb-1"><li class="list-inline-item"><a href="https://evileg.com/ru/users/mihail.dark/"><strong>Михаил Сермяжко</strong></a></li><li class="list-inline-item text-muted mr-2"><small>29 марта 2022 г. 15:42</small></li></ul><p class="mb-1"><a href="https://evileg.com/ru/forum/topic/1724/">Автоматически обновляться от QAbstractModel</a></p><div>   Добрый день.    Наследовал QAbstractModel на с++ и использую ее в QML. Как автоматом обновлять данные в QML при изменении данных в QAbstractModel?    Попробовал с помощью void emitSignalUpda…</div></div><script type="application/ld+json">{"@context": "http://schema.org", "@type": "Question", "author": "Михаил Сермяжко", "url": "/ru/forum/topic/1724/", "name": "Автоматически обновляться от QAbstractModel", "headline": "Автоматически обновляться от QAbstractModel", "description": "\n \n  Добрый день.\n  \n  Наследовал QAbstractModel на с++ и использую ее в QML. Как автоматом обновлять данные в QML при изменении данных в QAbstractModel?\n  \n  Попробовал с помощью void emitSignalUpdateModel();, но не получилось.\n \n \n  Q_PROPERTY для QML\n \n Q_PROPERTY(ModelRegistration* modelRegistration MEMBER m_modelRegistration CONSTANT)\n\n \n  .h\n \n #ifndef MODELREGISTRATION_H\n#define MODELREGISTRATION_H\n\n#include &lt;QObject&gt;\n#include &lt;QAbstractListModel&gt;\n\nstruct RegistrationObject\n{\n    RegistrationObject(int id, QString name, bool isDone) {\n        m_id = id;\n        m_name = name;\n        m_isDone = isDone;\n    }\n    int m_id;\n    QString m_name;\n    bool m_isDone;\n};\n\nclass ModelRegistration : public QAbstractListModel\n{\n    Q_OBJECT\npublic:\n    ModelRegistration(QObject *parent = nullptr);\n\n    enum RoleNames {\n        IdRole = Qt::UserRole,\n        NameRole,\n        IsDoneRole\n    };\n\n    QVector&lt;RegistrationObject&gt; vectorDataRegistration;\n\n    int rowCount(const QModelIndex&amp; parent = QModelIndex()) const override;\n    QVariant data(const QModelIndex&amp; index, int role = Qt::DisplayRole) const override;\n\npublic slots:\n    void emitSignalUpdateModel();\n\nprotected:\n    QHash&lt;int, QByteArray&gt; roleNames() const override;\n};\n\n#endif // MODELREGISTRATION_H\n\n \n  .cpp\n \n #include \"modelregistration.h\"\n\nModelRegistration::ModelRegistration(QObject *parent) : QAbstractListModel(parent)\n{\n    vectorDataRegistration.append(RegistrationObject(1, \"Legs (back)\", false));\n    vectorDataRegistration.append(RegistrationObject(2, \"Hips (back)\", false));\n    vectorDataRegistration.append(RegistrationObject(3, \"Back\", false));\n    vectorDataRegistration.append(RegistrationObject(3, \"Arms (back)\", false));\n    vectorDataRegistration.append(RegistrationObject(3, \"Hips (front)\", false));\n    vectorDataRegistration.append(RegistrationObject(4, \"Belly\", false));\n    vectorDataRegistration.append(RegistrationObject(3, \"Arms (front)\", false));\n}\n\nint ModelRegistration::rowCount(const QModelIndex &amp;parent) const\n{\n    return vectorDataRegistration.count();\n}\n\nQVariant ModelRegistration::data(const QModelIndex &amp;index, int role) const\n{\n    if (index.row() &lt; 0 || index.row() &gt;= vectorDataRegistration.count())\n        return QVariant();\n\n    switch (role)\n    {\n    case IdRole:\n        return vectorDataRegistration[index.row()].m_id;\n    case NameRole:\n        return vectorDataRegistration[index.row()].m_name;\n    case IsDoneRole:\n        return vectorDataRegistration[index.row()].m_isDone;\n    }\n\n    return QVariant();\n}\n\nvoid ModelRegistration::emitSignalUpdateModel()\n{\n    auto index = this-&gt;index(0);\n    emit dataChanged(index, index, QVector&lt;int&gt;{0,1,2});\n}\n\nQHash&lt;int, QByteArray&gt; ModelRegistration::roleNames() const\n{\n    QHash&lt;int, QByteArray&gt; roles;\n    roles[IdRole] = \"id\";\n    roles[NameRole] = \"name\";\n    roles[IsDoneRole] = \"isDone\";\n    return roles;\n}\n\n\n", "datePublished": "2022-03-29T08:42:29.265149+00:00", "interactionStatistic": [{"@type": "InteractionCounter", "interactionType": "BookmarkAction", "userInteractionCount": 0}, {"@type": "InteractionCounter", "interactionType": "LikeAction", "userInteractionCount": 0}, {"@type": "InteractionCounter", "interactionType": "DislikeAction", "userInteractionCount": 0}]}</script></div></div><div class="py-2"><div class="media"><a class="mr-3 text-decoration-none" href="https://evileg.com/ru/users/chunk/"><div class="m-0 p-0 position-relative"><div class="avatar-3 rounded-circle m-0 text-center virgin-amerika-gradient box-shadow"><div class="text-center align-middle w-100 h-100 avatar-initials text-uppercase avatar-initials-size-3">ИМ</div></div></div></a><div class="media-body"><ul class="list-inline mb-1"><li class="list-inline-item"><a href="https://evileg.com/ru/users/chunk/"><strong>Игорь Максимов</strong></a></li><li class="list-inline-item text-muted mr-2"><small>29 марта 2022 г. 2:53</small></li></ul><p class="mb-1"><a href="https://evileg.com/ru/forum/topic/1721/#post-9360">Прикрутить форму к админ-панели</a></p><div>   Между вывом кодирования из модели и из формы </div></div><script type="application/ld+json">{"@context": "http://schema.org", "@type": "Answer", "author": "Игорь Максимов", "url": "/ru/forum/topic/1721/#post-9360", "name": "Прикрутить форму к админ-панели", "headline": "Прикрутить форму к админ-панели", "description": "\n \n  Между вывом кодирования из модели и из формы\n \n", "datePublished": "2022-03-28T19:53:48.303311+00:00", "interactionStatistic": [{"@type": "InteractionCounter", "interactionType": "BookmarkAction", "userInteractionCount": 0}, {"@type": "InteractionCounter", "interactionType": "LikeAction", "userInteractionCount": 0}, {"@type": "InteractionCounter", "interactionType": "DislikeAction", "userInteractionCount": 0}]}</script></div></div><div class="py-2"><div class="media"><a class="mr-3 text-decoration-none" href="https://evileg.com/ru/users/Jamesglupe/"><div class="m-0 p-0 position-relative"><div class="avatar-3 rounded-circle m-0 text-center dark-knight-gradient box-shadow"><div class="text-center align-middle w-100 h-100 avatar-initials text-uppercase avatar-initials-size-3">J</div></div></div></a><div class="media-body"><ul class="list-inline mb-1"><li class="list-inline-item"><a href="https://evileg.com/ru/users/Jamesglupe/"><strong>Jamesglupe</strong></a></li><li class="list-inline-item text-muted mr-2"><small>25 марта 2022 г. 8:27</small></li></ul><p class="mb-1"><a href="https://evileg.com/ru/forum/topic/1692/#post-9341">Sorting the added QML elements in the ListModel</a></p><div>   Free slot play no download no registration  п»ї     gamesforrealmoney    usa online casino no deposit bonus code    Dead or alive 2 slot free play     freeslotgameswithbonusspins.blogspo…</div></div><script type="application/ld+json">{"@context": "http://schema.org", "@type": "Answer", "author": "Jamesglupe", "url": "/ru/forum/topic/1692/#post-9341", "name": "Sorting the added QML elements in the ListModel", "headline": "Sorting the added QML elements in the ListModel", "description": "\n \n  Free slot play no download no registration  п»ї\n  \n   gamesforrealmoney\n  \n  usa online casino no deposit bonus code\n  \n  Dead or alive 2 slot free play\n  \n   freeslotgameswithbonusspins.blogspot.com\n  \n  online casino free signup bonus no deposit required nz\n  \n  How to play poker in sleeping dogs\n  \n   slotmachinerealmoney.blogspot.com\n  \n  thunderbolt casino no deposit bonus codes 2021\n  \n  Automatenspiele kostenlos spielen ohne anmeldung book of ra\n  \n   bestslotsplaywheelingisland.blogspot.com\n  \n  free online casino win real money no deposit\n  \n  Free slots machines games to play online\n  \n   bestcasinosinlasvegas.blogspot.com\n  \n  casinos online 888 free casino games slot machines\n  \n  Kronos father of zeus slot machine free play\n  \n   slotmachineunderstanding.blogspot.com\n  \n  house of fun slots casino similar games\n  \n   https://klopslin.wixsite.com/play-poker-online\n  \n \n \n  \n   meeting online dating\n  \n \n", "datePublished": "2022-03-25T01:27:57.483642+00:00", "interactionStatistic": [{"@type": "InteractionCounter", "interactionType": "BookmarkAction", "userInteractionCount": 0}, {"@type": "InteractionCounter", "interactionType": "LikeAction", "userInteractionCount": 0}, {"@type": "InteractionCounter", "interactionType": "DislikeAction", "userInteractionCount": 0}]}</script></div></div></div></div></div><div class="col-12 col-lg-3 p-0 pb-3"><div class="sticky"><div class="card box-shadow m-2"><script async="" src="./Алгоритм DFS («Depth-first search» или «Поиск в глубину»)_files/f(4).txt"></script><!-- EVILEG COM Bottom --><ins class="adsbygoogle" style="display: block; height: 600px;" data-ad-client="ca-pub-8877856398367795" data-ad-slot="4520850861" data-ad-format="auto" data-full-width-responsive="true" data-adsbygoogle-status="done"><ins id="aswift_3_expand" style="border: none; height: 600px; width: 262px; margin: 0px; padding: 0px; position: relative; visibility: visible; background-color: transparent; display: inline-table;"><ins id="aswift_3_anchor" style="border: none; height: 600px; width: 262px; margin: 0px; padding: 0px; position: relative; visibility: visible; background-color: transparent; display: block;"></ins></ins></ins><script>
     (adsbygoogle = window.adsbygoogle || []).push({});
</script></div><!-- Yandex.RTB R-A-218837-2 --><div id="yandex_rtb_R-A-218837-2"><div></div></div><script type="text/javascript">
    (function(w, d, n, s, t) {
        w[n] = w[n] || [];
        w[n].push(function() {
            Ya.Context.AdvManager.render({
                blockId: "R-A-218837-2",
                renderTo: "yandex_rtb_R-A-218837-2",
                async: true
            });
        });
        t = d.getElementsByTagName("script")[0];
        s = d.createElement("script");
        s.type = "text/javascript";
        s.src = "//an.yandex.ru/system/context.js";
        s.async = true;
        t.parentNode.insertBefore(s, t);
    })(this, this.document, "yandexContextAsyncCallbacks");
</script></div></div></div></div><div class="container-fluid px-0 mx-0 py-3 row border-top small"><div class="col-12 col-lg-2"><h6>О нас</h6><ul class="fl"><li><a href="https://evileg.com/ru/pages/" target="_self">О сайте</a></li><li><a href="https://evileg.com/ru/pages/rules/privacy-policy/">Политика конфиденциальности</a></li><li><a href="https://evileg.com/ru/pages/contacts/">Контакты</a></li><li><a href="https://evileg.com/docs/evileg_core/" target="_blank">Документация</a></li><li><a href="https://github.com/EVILEG" target="_blank" rel="nofollow">GitHub</a></li><li><a href="https://evileg.com/ru/pages/donate/">Donate</a></li></ul></div><div class="col-12 col-lg-2"><h6>Услуги</h6><ul class="fl"><li><a href="https://evileg.com/ru/pages/for-advertisers/">Для рекламодателей</a></li></ul></div><div class="col-12 col-lg-2"><div class="mb-1">© EVILEG 2015-2021<br>Рекомендует хостинг <a href="http://timeweb.com/ru/?i=27415" target="_blank" rel="nofollow">TIMEWEB</a></div><a href="https://vk.com/evileg" class="vk-color" title="VK" rel="nofollow noopener noreferrer" target="_blank"><span class="mdi mdi-36px mdi-vk-box mdi-0"></span></a><a href="https://github.com/EVILEG" class="github-color" title="GitHub" rel="nofollow noopener noreferrer" target="_blank"><span class="mdi mdi-36px mdi-github-box mdi-0"></span></a><a href="https://www.youtube.com/c/EVILEG" class="youtube-color" title="YouTube" rel="nofollow noopener noreferrer" target="_blank"><span class="mdi mdi-36px mdi-youtube mdi-0"></span></a></div></div><script defer="" src="./Алгоритм DFS («Depth-first search» или «Поиск в глубину»)_files/prettify.js"></script><script defer="" src="./Алгоритм DFS («Depth-first search» или «Поиск в глубину»)_files/metrika.min.js"></script><noscript><img src="https://mc.yandex.ru/watch/39565770" style="position:absolute; left:-9999px;" alt="" /></noscript><div class="modal fade" id="share_on_social_networks" tabindex="-1" aria-hidden="true"><div class="modal-dialog modal-lg w-auto modal-content"><div class="modal-header"><span>Поделиться в социальных сетях</span><span class="mdi mdi-24px mdi-window-close mdi-0 pointer" data-dismiss="modal" aria-label="Close"></span></div><div class="modal-body"><a id="share_vk" href="https://evileg.com/ru/post/494/#" class="btn btn-dark btn-menu" target="_blank" rel="nofollow" onclick="window.open(this.href, &#39;Поделиться ссылкой в ВКонтакте&#39;, &#39;width=800,height=300&#39;); pages.clearCache(this.href); return false;"><div class="btn-menu-body"><div class="btn-menu-center"><div class="btn-menu-icon-offset"><span class="mdi mdi-36px mdi-vk-box mdi-0"></span></div><small>VKontakte</small></div></div></a><a id="share_facebook" href="https://evileg.com/ru/post/494/#" class="btn btn-dark btn-menu" target="_blank" rel="nofollow" onclick="window.open(this.href, &#39;Поделиться ссылкой в Facebook&#39;, &#39;width=640,height=436,toolbar=0,status=0&#39;); return false;"><div class="btn-menu-body"><div class="btn-menu-center"><div class="btn-menu-icon-offset"><span class="mdi mdi-36px mdi-facebook-box mdi-0"></span></div><small>Facebook</small></div></div></a><a id="share_twitter" href="https://evileg.com/ru/post/494/#" class="btn btn-dark btn-menu" target="_blank" rel="nofollow" onclick="window.open(this.href, &#39;Поделиться ссылкой в Twitter&#39;); return false;"><div class="btn-menu-body"><div class="btn-menu-center"><div class="btn-menu-icon-offset"><span class="mdi mdi-36px mdi-twitter-box mdi-0"></span></div><small>Twitter</small></div></div></a><a id="share_linkedin" href="https://evileg.com/ru/post/494/#" class="btn btn-dark btn-menu" target="_blank" rel="nofollow" onclick="window.open(this.href, &#39;Поделиться ссылкой в LinkedIn&#39;, &#39;width=800,height=600&#39;); return false;"><div class="btn-menu-body"><div class="btn-menu-center"><div class="btn-menu-icon-offset"><span class="mdi mdi-36px mdi-linkedin-box mdi-0"></span></div><small>LinkedIn</small></div></div></a></div></div></div><div id="shadow" class="shadow" onclick="$(&#39;body&#39;).toggleDrawer();"></div>
<ins class="adsbygoogle adsbygoogle-noablate" data-adsbygoogle-status="done" style="display: none !important;" data-ad-status="unfilled"><ins id="aswift_4_expand" style="border: none; height: 0px; width: 0px; margin: 0px; padding: 0px; position: relative; visibility: visible; background-color: transparent; display: inline-table;" tabindex="0" title="Advertisement" aria-label="Advertisement"><ins id="aswift_4_anchor" style="border: none; height: 0px; width: 0px; margin: 0px; padding: 0px; position: relative; visibility: visible; background-color: transparent; display: block;"><iframe id="aswift_4" name="aswift_4" style="left:0;position:absolute;top:0;border:0;width:undefinedpx;height:undefinedpx" sandbox="allow-forms allow-popups allow-popups-to-escape-sandbox allow-same-origin allow-scripts allow-top-navigation-by-user-activation" frameborder="0" marginwidth="0" marginheight="0" vspace="0" hspace="0" allowtransparency="true" scrolling="no" src="./Алгоритм DFS («Depth-first search» или «Поиск в глубину»)_files/ads(3).html" data-google-container-id="a!5" data-load-complete="true"></iframe></ins></ins></ins><div style="position: fixed; left: -99px;"><div id="b5796c3e1f"><iframe frameborder="no" scrolling="no" allowtransparency="true" hidefocus="true" tabindex="-1" marginwidth="0" marginheight="0" src="./Алгоритм DFS («Depth-first search» или «Поиск в глубину»)_files/render.html" id="id2817" style="opacity: 1;"></iframe></div></div><iframe src="./Алгоритм DFS («Depth-first search» или «Поиск в глубину»)_files/aframe.html" width="0" height="0" style="display: none;"></iframe></body><style id="stylus-1" type="text/css" class="stylus">body {
    font-family: 'pragmata pro mono regular';
}</style><iframe id="google_esf" name="google_esf" src="./Алгоритм DFS («Depth-first search» или «Поиск в глубину»)_files/zrt_lookup.html" style="display: none;"></iframe></html>